实体框架 - 外键注释被忽略获取错误的对象

时间:2016-04-07 10:20:10

标签: c# entity-framework

强制性的“第一次问题,抱歉,如果我搞砸了”。我希望有人可以提供帮助。

实体框架6,.net 4.5。

我有一个产品。产品可能由特定数量的其他产品制成,因此我创建了一个ProductUsed类,其中包含两个productID,一个名为ParentProductID,另一个名为PreProductID,在虚拟产品上带有注释,指向“PreProductID”的外键。每次我访问它时,它都会为ParentProductID加载产品。

public class Product
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProductID { get; set; }

    [Required]
    [Display(Name = "Name")]
    public string ProductName { get; set; }

//trimmed for brevity 

    [ForeignKey("ParentProductID")]
    public virtual List<ProductUsed> ProductsUsed { get; set; }

}

public class ProductUsed
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProductUsedID { get; set; }

    [Display(Name = "Pre Product")]
    [Required]
    public int PreProductID { get; set; }

    [Display(Name = "Pre Product")]
    [ForeignKey("PreProductID")]
    public virtual Product PreProduct { get; set; }

    [Display(Name = "Product")]
    [Required]
    public int ParentProductID { get; set; }

    public int Quantity { get; set; }


}

通过创建对象,将其添加到父产品ProductsUsed集合,然后保存更改来完成保存。数据库的所有字段都在正确的位置。

我读过的所有内容都说这应该是直截了当的,它似乎忽略了注释。或者(完全更可能)我不明白该注释应该如何工作。

任何指针?

1 个答案:

答案 0 :(得分:0)

The problem is you have your foreign key in the wrong model. It should look like this:

public class Product
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProductID { get; set; }

    [Required]
    [Display(Name = "Name")]
    public string ProductName { get; set; }

    public virtual List<ProductUsed> ProductsUsed { get; set; }

    public virtual List<ProductUsed> PreProducts { get; set; }

}

public class ProductUsed
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProductUsedID { get; set; }

    [Display(Name = "Pre Product")]
    [Required]
    public int PreProductID { get; set; }

    [Display(Name = "Pre Product")]
    public virtual Product PreProduct { get; set; }

    [Display(Name = "Product")]
    [Required]
    public int ParentProductID { get; set; }

    public virtual Product ParentProduct { get; set; }

    public int Quantity { get; set; }


}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProductUsed>()
            .HasRequired(p => p.ParentProduct)
            .WithMany(p => p.ProductsUsed)
            .HasForeignKey(p => p.ParentProductID);
        modelBuilder.Entity<ProductUsed>()
            .HasRequired(p => p.PreProduct)
            .WithMany(p => p.PreProducts)
            .HasForeignKey(p => p.PreProductID)
            .WillCascadeOnDelete(false);
    }

The ProductsUsed in Product is then resolved by the foreign key in ProductUsed model.

EDIT: Changed to fluent api model builder.