代码优先关系

Code First Relationships

我在先使用代码时遇到了一些意想不到的结果,我知道这与 EF 如何创建关系有关,但我无法弄清楚。这是我的。

Product class,KitComponent class(包含产品和数量等) 一个产品有很多 KitComponents 一个 KitComponent 有很多 Products

最终结果是展示一个产品,这个产品还有一些其他产品作为套件包含在内。它可能包含 1 个产品或 2 件,这就是为什么我需要一个 KitComponent class / table 来保存其他信息。

我在 ef 关系中挣扎的时间最长。数据库会将 ParentProductId 和 Parent Product 放入 IncludedProductID 和 IncludedProduct。现在我修复了它,但不知道如何修复 IncludedProduct 字段未被填充。 IncludedProductID 现在在数据库中是正确的。我缺少什么,所以当我拉出一个产品并循环浏览 IncludedProduct 不为空的 kitCOMponents 时。

除此之外,我是否正确描述了配置中的关系?

产品:

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; }
}

套件组件:

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();
    }
}

为了加载 属性,您必须将导航 属性 设为虚拟:

public virtual Product IncludedProduct { get; set; }

所有代码优先约定都可以在这里找到:https://msdn.microsoft.com/en-us/data/jj679962.aspx