实体框架导航属性为null

时间:2012-11-02 17:26:51

标签: entity-framework ef-code-first entity-framework-5

我有两个简单的课程:

public class Setting
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid SettingId { get; set; }

    [Required]
    public String Name { get; set; }

    public String Value { get; set; }

    [Required]
    public SettingCategory SettingCategory { get; set; }
}

public class SettingCategory
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid SettingCategoryId { get; set; }

    [Required]
    public String Value { get; set; }

    public ICollection<Setting> Settings { get; set; }
}

当我从数据库中检索SettingCategory时,集合设置始终为空。

当我将其设为virtual时,它会说:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

如何访问我的Settings列表?

另一种方法是,如果我从数据库中检索Setting,则会填充SettingCategory属性。

这是我最初的代码迁移脚本:

CreateTable(
    "dbo.Settings",
    c => new
        {
            SettingId = c.Guid(nullable: false, identity: true),
            Name = c.String(nullable: false),
            Value = c.String(),
            SettingCategory_SettingCategoryId = c.Guid(nullable: false),
        })
    .PrimaryKey(t => t.SettingId)
    .ForeignKey("dbo.SettingCategories", t => t.SettingCategory_SettingCategoryId, cascadeDelete: true)
    .Index(t => t.SettingCategory_SettingCategoryId);

CreateTable(
    "dbo.SettingCategories",
    c => new
        {
            SettingCategoryId = c.Guid(nullable: false, identity: true),
            Value = c.String(nullable: false),
        })
    .PrimaryKey(t => t.SettingCategoryId);

这是从数据库中获取它的部分:

public SettingCategory Get(Guid settingCategoryId)
{
    using (var context = new BackofficeContext())
    {
        return context
            .SettingCategories
            .FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
    }
}

答案

我忘记了.SettingCategories中的包含,但我正在尝试使用lambda:

public SettingCategory Get(Guid settingCategoryId)
{
    using (var context = new BackofficeContext())
    {
        return context
            .SettingCategories
            .Include(s => s.Settings)
            .FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
    }
}

这不起作用,但确实如此:

public SettingCategory Get(Guid settingCategoryId)
{
    using (var context = new BackofficeContext())
    {
        return context
            .SettingCategories
            .Include("Settings")
            .FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
    }
}

1 个答案:

答案 0 :(得分:16)

因为您正在处置BackofficeContext,所以您无法使用LazyLoading,这就是虚拟Settings时发生的情况。

您可以延长BackofficeContext或急切加载Settings的生命周期。您可以使用Include预先加载。

public SettingCategory Get(Guid settingCategoryId)
{
    using (var context = new BackofficeContext())
    {
        return context
            .SettingCategories
            .Include(s => s.Settings)
            .FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
    }
}