A specified Include path is not valid. The EntityT

2019-03-06 10:42发布

问题:

I wonder if you could help. I get the above error when I call .Include(). It breaks when I include tblMemberships.

this.dbContext.Configuration.LazyLoadingEnabled = false;
List<tblCustomerInfo> customers = this.dbContext.tblCustomerInfoes.Include("tblUsers").Include("tblMemberships").ToList();

The reason is because the navigation property between tblCustomerInfo and tblMemberships does not exist. tblUsers is the link between the other two tables.

Customer -- 1:* -- User -- 1:* -- Membership

(Sorry, can't include image as my reputataion < 10).

My questions are:

  1. What do I need to do in order to have tblMemberships included?
  2. Is this a recommended way of retrieve data or I should break it up into two queries? Or the design is totally rubbish?

I am using EF5, ASP .NET MVC 4

Kindly advise. Thank you.

回答1:

When you write code like this:

db.ParentTable
    .Include("ChildTable")
    .Include("ChildOfChildTable");

You are saying include all entries from ChildTable that are keyed to ParentTable and also include all entries from ChildOfChildTable that are ALSO keyed to ParentTable. Instead you need to tell Entity Framework that ChildOfChildTable is beneath ChildTable in the hierarchy, like this:

db.ParentTable
    .Include("ChildTable.ChildOfChildTable");

So this means your code should be:

this.dbContext.Configuration.LazyLoadingEnabled = false;
List<tblCustomerInfo> customers = this.dbContext.tblCustomerInfoes
                                      .Include("tblUsers.tblMemberships")