我有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