I have two tables called ShipmentType and Books. Entity class has been mapped for these tables. Created another class called BookShipment which contains two properties, classes of ShipmentType and Book.
public class BookShipment
{
public ShipmentType Shipment { get; set; }
public Books Book { get; set; }
}
I was trying to create a where expression as follows.
Expression<Func<BookShipment, bool>> expr = x => (x.Shipment.ID == 1 && x.Book.ID == 1);
var result = from c in styp
join d in book
on c.ID equals d.ID
select new BookShipment { Shipment = c, Book = d };
var List = result.Where(expr).ToList();
and above expression at where clause is working fine and getting the result from database.
Tried to create a dynamic expression same as above expr expression but it is giving error.
BookShipment table = new BookShipment();
table.Shipment = new ShipmentType();
table.Book = new Books();
ParameterExpression ParameterL = Expression.Parameter(table.GetType(), "x");
ParameterExpression Parameter1 = Expression.Parameter(table.Shipment.GetType(), "x.Shipment");
ParameterExpression Parameter2 = Expression.Parameter(table.Book.GetType(), "x.Book");
var Property1 = Expression.Property(Parameter1, "ID");
var Property2 = Expression.Property(Parameter2, "ID");
var Clause1 = Expression.Equal(Property1, Expression.Constant(1));
var Clause2 = Expression.Equal(Property2, Expression.Constant(1));
var Lambda1 = Expression.Lambda<Func<ShipmentType, bool>>(Clause1, Parameter1);
var Lambda2 = Expression.Lambda<Func<Books, bool>>(Clause2, Parameter2);
var OrElseClause = Expression.Or(Lambda1.Body, Lambda2.Body);
var Lambda = Expression.Lambda<Func<BookShipment, bool>>(OrElseClause, ParameterL);
var result = from c in styp
join d in book
on c.ID equals d.ID
select new BookShipment { Shipment = c, Book = d };
var record = result.Where(Lambda).ToList();
When executing above Where clause it is giving error.
{System.InvalidOperationException: The LINQ expression 'DbSet<ShipmentType>
.Join(
outer: DbSet<Books>,
inner: s => s.ID,
outerKeySelector: b => b.BookID,
innerKeySelector: (s, b) => new TransparentIdentifier<ShipmentType, Books>(
Outer = s,
Inner = b
))
.Where(ti => ti.Shipment.ID == 1 || ti.Book.BookID == 1)' could not be translated.