mam 2 proste klasy:Podmiot nieruchomość nawigacja ramy jest 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; }
}
Kiedy pobrać SettingCategory
z bazy Ustawienia kolekcji jest zawsze zerowa.
Kiedy sprawiają, że virtual
wtedy powie: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Jak mogę uzyskać dostępu do listy Settings
?
Na odwrót, jeśli pobierze się Setting
z bazy danych, zostanie wypełniona właściwość SettingCategory
.
To jest moje pierwsze skrypt kodu migracje:
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);
I to jest ta część, która pobiera go z bazy danych:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
odpowiedzi
Zapomniałem m.in. w .SettingCategories
, ale próbowałem go z lambda:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.Include(s => s.Settings)
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
To nie działa, ale to robi:
public SettingCategory Get(Guid settingCategoryId)
{
using (var context = new BackofficeContext())
{
return context
.SettingCategories
.Include("Settings")
.FirstOrDefault(s => s.SettingCategoryId == settingCategoryId);
}
}
To jest dziwne. Czy możesz pokazać, jak pobierasz SettingCategory? – Anri
Czy na pewno masz powiązane ustawienia w swojej bazie danych? – Anri
Korzystam najpierw z Code z migracjami, więc wszystko powinno być w porządku? Dodałem mój skrypt początkowy. – YesMan85