C# 4.0 实体框架-代码优先';加载引用对象
首先,我有两个由代码生成的简单类C# 4.0 实体框架-代码优先';加载引用对象,c#-4.0,entity-framework-4,code-first,ef-code-first,C# 4.0,Entity Framework 4,Code First,Ef Code First,首先,我有两个由代码生成的简单类 public class Company { public int Id { get; set; } public string Name { get; set; } public virtual Address Address { get; set; } } public class Address { public int Id { get; set; } public string Country { get; s
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Country { get; set; }
...
}
将公司保存到数据库中后,我有了公司(Id=1 | name=“blah”| AddressId=1)及其地址(Id=1,Country=“波兰”)。当我尝试从DbContext加载时:
Company company = context.Companies.Find(id);
我得到一个空地址属性的公司。我做错了什么
(我正在使用CTP5。)试试这个:
Company company = context.Companies.Include("Address").Find(id);
或者使用新的类型化语法:
Company company = context.Companies.Include(c => c.Address).Find(id);
这告诉EF急切地加载地址
实体作为您的公司
实体的一部分
似乎您的存储库层位于EF之上-如果是这样,请确保您的存储库实现支持Include()
首先,这是Julia Lerman在“Programming Entity Framework”中提供的Include()
的实现,用于支持POCO的单元可测试存储库模式(此版本仅适用于第一种语法):
公共静态IQueryable包含(此IQueryable源,字符串路径)
{
var objectQuery=源作为objectQuery;
if(objectQuery!=null)
{
返回objectQuery.Include(路径);
}
返回源;
}
Btw.不要使用CTP5已经有EF 4.1 RC,它有API的“最终”版本:您是如何访问地址的
。应该会触发延迟加载。我已检查了我的版本。我有EntityFramework.dll运行时版本v4.0.30319和版本4.0.0.0。当我使用nuget时,我已经安装了“PM>安装包EntityFramework”EntityFramework 4.1.10311.0。I-mo已经引用了“EntityFramework 4.1.10311.0”。“这很奇怪,延迟加载仍然无法工作。您是否关闭了延迟加载或代理创建?Aaaa。。。我确信答案是否定的,但在运行时,事实证明这是正确的。我在某个地方发现,对于测试,我将LazyLoadingEnabled设置为false。我真丢脸。。。非常感谢您抽出时间!或者,您也可以使用更通用的自定义扩展来包括:
public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
var objectQuery = source as ObjectQuery<TSource>;
if (objectQuery != null)
{
return objectQuery.Include(path);
}
return source;
}