Hal*_*him 6 c# entity-framework foreign-key-relationship ef-code-first entity-framework-5
我想在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);
}
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
产品类如下
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; }
}
Run Code Online (Sandbox Code Playgroud)
品牌类如下:
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; }
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
如果您尚未将品牌和类别声明为虚拟,则延迟加载品牌和类别属性将不起作用.
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; }
}
Run Code Online (Sandbox Code Playgroud)
见这对懒惰和渴望加载更多的信息.
| 归档时间: |
|
| 查看次数: |
7237 次 |
| 最近记录: |