我試圖關係添加到網頁API項目中使用EF代碼第一次我的實體實體框架代碼優先 - 關係
我的數據庫種子碼是
internal class ProductDbInitializer : DropCreateDatabaseAlways<ProductDbContext>
{
protected override void Seed(ProductDbContext context)
{
Category category = new Category();
LanguagesDbContext languagesDbContext = new LanguagesDbContext();
List<Language> languages = new List<Language>
{
new Language {Name="English",Code="en" },
new Language {Name="Italian", Code="it" },
new Language {Name="Russian",Code="rus" },
};
languagesDbContext.Languages.AddRange(languages);
context.Categories.Add(category);
List<CategoryText> categoryText = new List<CategoryText>();
foreach (var language in languages)
{
string name = string.Empty;
switch (language.Code)
{
case "en":
name = "paper";
break;
case "it":
name = "carta";
break;
case "rus":
name = "бумага";
break;
default:
name = "paper";
break;
}
categoryText.Add(new CategoryText
{
Category = category,
Language = language,
Name = name
});
}
category.CategoryTexts.Add(categoryText[1]);
context.CategoryTexts.AddRange(categoryText);
context.SaveChanges();
}
}
一切都存儲在數據庫,我想在我的課的申報問題,因爲當我想Categories
我沒有能夠看到CategoryTexts
這是瀏覽器輸出
但在數據庫中,我的CategoryTexts
已添加有效的CategoryId
。
這是我的類別和CategoryText實體
public class Category
{
public Category()
{
CategoryTexts = new List<CategoryText>();
}
public int Id { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<CategoryText> CategoryTexts { get; set; }
}
和
public class CategoryText
{
public int Id { get; set; }
public int CategoryId { get; set; }
public int LanguageId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
public string Name { get; set; }
}
請幫助我理解我在哪裏需要更改代碼
所以如果我標記作爲虛擬它會自動添加? –
是的,如果你有延遲加載和代理生成,並且在訪問引用時上下文仍然可用(不處理),它會加載它 – Jcl
非常感謝你的信息,你是英雄 –