Include Statement With Linq Join

c# entity-framework linq

Question

IQueryable<Employee> emps = CreateObjectSet<Employee>()
                                  .Include(u => u.Departments)
                                  .AsQueryable();
IQueryable<Products> prods = CreateObjectSet<Products>().AsQueryable();

CreateObjectSet is ObjectContext's CreateObjectSetMethod

        return (from emp in emps
                join prod in prods
                on emp.ProductID equals prod.ProductID
                where emp.EmployeeID == 10
                select employee).ToList();

The problem is from the first line, i use the include statement and include departments with the employees the return values does not have departments with as they are never included. Kindly suggest something.

This is just a demo query, actual query is far complex, so please don't suggest that i should not go with the join statement, but simple include and where clause, that does not serve me ni my scenario.

Thanks

1
12
2/22/2018 9:12:09 PM

Accepted Answer

This is a known issue with include. You could have a look at the following article Include in EF

> var results =
>         ((from post in ctx.Posts
>         from blog in post.Blogs
>         where blog.Owner.EmailAddress == “alexj@microsoft.com”
>         select post) as ObjectQuery<Post>).Include(“Comments”);

If that solution won't work for you, you can also try to fix it with grouping your data and selecting the departments as one of the values in your type.

The EF entity relation fixup mechanism will then 'fix' the include for you.

15
2/22/2018 7:38:06 PM

Popular Answer

This can be solved with the following code:

var query = from emp in emps
            join prod in prods
            on emp.ProductID equals prod.ProductID
            where emp.EmployeeID == 10
            select employee;
var result = query.Include(u => u.Departments)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow