我在使用代码时遇到了一些意想不到的结果,我知道它与EF如何创建关系有关,但我无法弄明白。这就是我所拥有的。
产品类,KitComponent类(持有产品和数量等) 产品有许多KitComponents KitComponent有很多产品
最终结果是展示产品,此产品还包含一些其他产品作为套件。它可能包含1个产品或2个产品,这就是为什么我需要一个KitComponent类/表来保存其他信息。
在最长的时间里,我与ef关系挣扎。数据库将ParentProductId和Parent Product放入IncludedProductID和IncludedProduct。现在我修复了但不知道如何填充IncludedProduct字段。 IncludedProductID现在在数据库中是正确的。我错过了什么,以便当我拉出产品并在kitCOmponents中循环时,IncludedProduct不为空。
最重要的是,我是否正确描述了配置中的关系?
产品:
public class Product
{
public Product()
{
this.KitComponents = new HashSet<KitComponent>();
}
public int Id { get; set; }
public string PartNumber { get; set; }
public virtual ICollection<KitComponent> KitComponents { get; set; }
}
KitComponent:
public class KitComponent
{
public int Id { get; set; }
public string UOM { get; set; }
public int QTY { get; set; }
public int ParentProductId { get; set; }
public Product ParentProduct { get; set; }
public int IncludedProductId { get; set; }
public Product IncludedProduct { get; set; }
}
DBContext使用流畅的API代码:
public class ProductContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<KitComponent> KitComponents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasMany(p => p.KitComponents)
.WithRequired(k => k.ParentProduct)
.HasForeignKey(p => p.ParentProductId);
modelBuilder.Entity<KitComponent>().HasRequired(k => k.IncludedProduct)
.WithMany()
.HasForeignKey(k => k.IncludedProductId)
.WillCascadeOnDelete(false);
}
}
演示数据的简单种子方法:
public class ProductContextInitializer : DropCreateDatabaseAlways<ProductContext>
{
private ProductContext db = new ProductContext();
protected override void Seed(ProductContext context)
{
Product prod1 = new Product { PartNumber = "P1" };
Product prod2 = new Product { PartNumber = "P2" };
Product prod3 = new Product { PartNumber = "P3" };
Product prod4 = new Product { PartNumber = "P4" };
Product prod5 = new Product { PartNumber = "P5" };
Product prod6 = new Product { PartNumber = "P6" };
Product prod7 = new Product { PartNumber = "P7" };
db.Products.Add(prod1);
db.Products.Add(prod2);
db.Products.Add(prod3);
db.Products.Add(prod4);
db.Products.Add(prod5);
//db.Products.Add(prod6);
//db.Products.Add(prod7);
db.SaveChanges();
var kitComp = new KitComponent() { IncludedProduct = prod2, QTY = 1, UOM = "EA" };
prod1.KitComponents.Add(kitComp);
db.SaveChanges();
}
}
答案 0 :(得分:0)
要加载属性,必须将导航属性设为虚拟:
public virtual Product IncludedProduct { get; set; }
可以在此处找到所有代码优先约定:https://msdn.microsoft.com/en-us/data/jj679962.aspx