我有 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);
}
}