[英]Entity Framework 5 codefirst / Required and optional foreign key relations are null
我想在entityframework5 codefirst方式上用我的entites創建一個DbContext。 我有品牌,類別和產品。
但是當我嘗試獲取Product
它的Brand
和Category
字段為空。 Category
是可選的,但Brand
不是。 所以至少必須設置品牌領域。 我試過下面的代碼。 有什么我想念的嗎?
public DbSet<Brand> Brands { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Brand>()
.HasMany(b => b.Products)
.WithRequired(p => p.Brand)
.HasForeignKey(p => p.BrandId);
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithOptional(p => p.Category)
.HasForeignKey(p => p.CategoryId);
}
在MVC控制器方面:
using (var db = new InonovaContext())
{
var product = db.Products.Single(p => p.Id == id);
model.Description = product.Description;
model.ImageUrl = product.ImageUrl;
model.Name = product.Name;
model.BreadCrumb = product.Brand.Name + " / " + product.Category == null ? "" : (product.Category.Name + " / ") + product.Name; // Here Brand and Category are null
}
產品類如下
public class Product
{
public int Id { get; set; }
public int BrandId { get; set; }
public virtual Brand Brand { get; set; }
public string Name { get; set; }
public int? CategoryId { get; set; }
public virtual Category Category { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
}
品牌類如下:
public class Brand
{
public int Id { get; set; }
public string Name { get; set; }
public string ThumbLogoImageUrl { get; set; }
public string Description { get; set; }
public ICollection<Product> Products { get; set; }
}
謝謝。
如果您尚未將品牌和類別聲明為虛擬,則延遲加載品牌和類別屬性將不起作用。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Brand Brand { get; set; }
public int BrandId { get; set; }
public virtual Category Category { get; set; }
public int? CategoryId { get; set; }
}
見這對懶惰和渴望加載更多的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.