问题
I am converting linq2sql to entity framework.
During the conversion I needed to convert the loadwith of linq2sql with include for eagar loading, but the eager loading is not working. When I used the profiler, I found that the child entities are loaded with they are accessed.
DataBaseEntities context = new V3C_DataBaseEntities();
context.Agents.Include("Account");
Agent ag = context.Agents.Where(x => x.Login_ID == "2").SingleOrDefault();
// here the account should have been loaded,
// but actually they are loaded with the line below this is executed.
Console.WriteLine(ag.Account.ID.ToString());
If do the following, It works perfectly, but I must do the way mentioned in the question.
var c = (from ag in context.Agents.Include("Account")
where ag.Login_ID == "2"
select ag).SingleOrDefault();
I would also like a type safe way of loading child entities.
回答1:
You can't do that as you wrote in question. You must use include in query. There is no smooth manner when transforming from Linq2Sql to EF. You must accept new API and use it correctly.
You can use only this:
var query = context.Agents.Include("Account");
Agent ag = query.Where(x => x.Login_ID == "2").SingleOrDefault();
If you want type safe Include version you must download Entity Framework Feature CTP5 or write your own extension.
回答2:
This is your query which does not perform the eager load:
context.Agents.Include("Account");
Agent ag = context.Agents.Where(x => x.Login_ID == "2").SingleOrDefault();
If you change the query to place the Include
within the expression I believe you will get the results you want.
Agent ag = context.Agents
.Include("Account")
.Where(x => x.Login_ID == "2").SingleOrDefault();
In my testing, and I have looked at the resulting generated SQL, the first expression does not join in the related table. Your Include
is ignored because it is not part of the query expression.
来源:https://stackoverflow.com/questions/5173890/entity-framework-4-eager-loading-not-working-at-all