6

我有 2 个简单的课程:

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从数据库中检索 a 时,集合设置始终为空。

当我把它变成一个virtual然后它会说:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

如何访问我的Settings列表?

另一种方法是,如果我Setting从数据库中检索 a ,则该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);
    }
}

回答

我忘记了 include in .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);
    }
}
4

1 回答 1

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);
    }
}
于 2012-11-02T17:47:52.630 回答