开发者

Using .Include() when joining a view using Entity Framework [duplicate]

开发者 https://www.devze.com 2023-01-21 16:23 出处:网络
This question already has answers here: Why doesn't Include have any effect? (2 answers) Closed 4 years ago.
This question already has answers here: Why doesn't Include have any effect? (2 answers) Closed 4 years ago.

Im using an Indexed View which is an entity without any relations (relations to my table entities would be preferable but this seemed to be nearly impossible to achieve). This view consists of 4 FK's which together form the PK:

PortalID
CategoryID
BranchID
CompanyID

Now im joining this view to select a set of companies like this:

var companies = (from c in database.Companies.FindAll().Include("City")
                 join l in database.CompanyList.FindAll() on c.ID equals l.CompanyID
                 where l.PortalID == 9 && l.BranchID == 1597
                 select c).Take(10);

The entity Company has an association with the table Cities (CityID, City), which i want to Include and works perfectly. However when i join the view the .Include() is ignored completely and t开发者_如何学Pythonhus results in a query without a join to the cities table.

As you might have concluded im using a repository pattern and FindAll() returns an IQueryable and ive manually added the Include extension to IQueryable like this:

public static IQueryable<T> Include<T>(this IQueryable<T> sequence, string path) {
    var objectQuery = sequence as ObjectQuery<T>;
    if (objectQuery != null)
        return objectQuery.Include(path);

    return sequence;
}

Ive thoroughly tested this extension and works like it should.

So now for my question, why is it ignoring the Include operation in the final expression tree and how can i prevent it from doing so?

UPDATE:

I got my solution from the following link: http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx

Which says i need to rewrite my query like this:

var companies = (from c in database.Companies.GetAll()
                 join l in database.CompanyList.GetAll() on c.ID equals l.CompanyID
                 where l.PortalID == 9 && l.BranchID == 1597
                 select c).Include("City").Take(10);


the answer to your question why is it ignoring the Include operation in the final expression? because when you join The Companies Table with CompanyList the result entity type of this join operation is new type contains both entities types primitive type properties only But if you want to include cities you have to cast result type to Company Type then call include City of this cast type.

0

精彩评论

暂无评论...
验证码 换一张
取 消