Entity Framework 4 eager loading not working at all!

回眸只為那壹抹淺笑 提交于 2020-01-17 05:06:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!