实体框架4急切加载根本不工作!

时间:2011-03-02 21:44:25

标签: entity-framework-4 entity

我正在将linq2sql转换为实体框架。

在转换过程中,我需要转换带有包含eagar加载的linq2sql的loadwith,但是急切加载不起作用。当我使用分析器时,我发现子实体已加载它们被访问。

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());

如果执行以下操作,它可以完美地运行,但我必须按照问题中提到的方式进行操作。

var c = (from ag in context.Agents.Include("Account")
                     where ag.Login_ID == "2"
                     select ag).SingleOrDefault();

我还想要一种加载子实体的类型安全方法。

2 个答案:

答案 0 :(得分:4)

你不能像你写的那样做。您必须在查询中使用包含。从Linq2Sql转换为EF时没有流畅的方式。您必须接受新API并正确使用它。

你只能使用这个:

var query = context.Agents.Include("Account");
Agent ag = query.Where(x => x.Login_ID == "2").SingleOrDefault(); 

如果您想要类型安全包含版本,则必须下载Entity Framework Feature CTP5或撰写own extension

答案 1 :(得分:0)

这是您的查询,它不执行急切加载:

context.Agents.Include("Account");

Agent ag = context.Agents.Where(x => x.Login_ID == "2").SingleOrDefault();

如果您更改查询以将Include置于表达式中,我相信您将获得所需的结果。

Agent ag = context.Agents
                  .Include("Account")
                  .Where(x => x.Login_ID == "2").SingleOrDefault();

在我的测试中,我查看了生成的SQL,第一个表达式没有加入相关表。您的Include将被忽略,因为它不是查询表达式的一部分。

相关问题