实体框架 - 导航属性不加载

时间:2013-04-15 14:43:49

标签: entity-framework entity-framework-4 foreign-keys eager-loading

我有以下关系

enter image description here

public partial class SharedResource : DomainEntity
{
    public System.Guid Id { get; set; }
    public System.Guid VersionId { get; set; }

    public virtual PackageVersion PackageVersion { get; set; } // tried it noth with and without virtual
}

现在,我使用

加载SharedResource
SharedResource sharedResource = Get(shareKey)

并且

sharedResource.PackageVersion == null. 

虽然VersionId不为null且

context.Configuration.LazyLoadingEnabled = false;

为了加载它我该怎么做

1 个答案:

答案 0 :(得分:6)

LazyLoadingEnabled必须是true,而不是false

context.Configuration.LazyLoadingEnabled = true;
如果您根本没有设置true,则

LazyLoadingEnabled是默认设置。

PackageVersion属性必须为virtual才能为此属性启用延迟加载。

或者您可以直接在查询中包含该属性:

SharedResource sharedResource = context.SharedResource
    .Include("PackageVersion")
    .SingleOrDefault(s => s.Id == shareKey);