I am getting the problem with "Include" in Entity Framework. Lets assume that I have two tables with foreign key relation.
var result = (from u in entity.Table1.Include("Table2")
join o in entity.Table2 on u.Column1 equals o.Column1
where u.Column2 == “abc” && u.Column3 == ‘xyz’
&& o.Column5 == organizationCode
select u).FirstOrDefault();
With the above query its not returning the Table2 object data in the result even though I have proper data in the database.
The issue i have found with above query is, if query is having "Include" as well as "Join", EF not considering "Include" tables. This is my assumption.
After spending some time I got the data by writing a dummy query below that. Please see the both queries below.
var result = (from u in entity.Table1.Include("Table2")开发者_运维百科
join o in entity.Table2 on u.Column1 equals o.Column1
where u.Column2 == “abc” && u.Column3 == ‘xyz’
&& o.Column5 == organizationCode
select u).FirstOrDefault();
var resultOrg = (from o in entity. Table2
where o.Column5 == organizationCode
select o).FirstOrDefault();
After executing both queries I am getting the Include (Table2) data in the result variable. In this case unnecessarily I am executing one query which I want to avoid.
Please suggest me where we are doing wrong.You cannot use Include
if you are using join
. There is now way around that. Moreover what you are trying to do is filtering include which is also not possible.
You can do this:
var result = (from u in entity.Table1.Include("Table2")
where u.Column2 == “abc” && u.Column3 == ‘xyz’ &&
u.Table2.Any(o => o.Column5 == organizationCode)
select u).FirstOrDefault();
But it will include all Table2
entities to filtered Table1
entities. You cannot restrict included values to only those having some organization code.
To filter navigation properties you must use projection:
var result = (from u in entity.Table1
where u.Column2 == “abc” && u.Column3 == ‘xyz’ &&
u.Table2.Any(o => o.Column5 == organizationCode)
select new
{
Table1 = u
Table2 = u.Table2.Where(o => o.Column5 == organizationCode)
}).FirstOrDefault();
You must project either to anonymous type or custom type.
The reason why your second query works is automatic wiring of relations for tracked properties and it is another way how to filter relations but in such case this is enough:
var result = (from u in entity.Table1
where u.Column2 == “abc” && u.Column3 == ‘xyz’ &&
u.Table2.Any(o => o.Column5 == organizationCode)
select u).FirstOrDefault();
var resultOrg = (from o in entity. Table2
where o.Column5 == organizationCode
select o).FirstOrDefault();
精彩评论