我有2个简单的类:实体框架导航属性为null
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
,但我试着用拉姆达:
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);
}
}
这很奇怪。你能展示你如何检索SettingCategory? – Anri
你确定你的数据库中有相关的设置吗? – Anri
我使用代码首先进行迁移,所以它应该使一切正常?我添加了我的初始脚本。 – YesMan85