生成EF 5 Code First额外外键

时间:2015-05-26 11:49:50

标签: c# entity-framework-5

有时EF会在生成的表中包含* _Id外键,即使我指定了外键。

类:

public partial class Product : IFoo, IBar
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [XmlIgnore, ScriptIgnore, ForeignKey("InsuranceClassId"), Display(Name = "Insurance Class")]
    public virtual InsuranceClass InsuranceClass { get; set; }
    [Display(Name = "Insurance Class")]
    public int InsuranceClassId { get; set; }

    [XmlIgnore, ScriptIgnore, ForeignKey("ProductGroupId"), Display(Name = "Product Group")]
    public virtual ProductGroup ProductGroup { get; set; }
    [Display(Name = "Product Group")]
    public int ProductGroupId { get; set; }

    //[Snip]
}

public partial class InsuranceClass : IFoo, IBar
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [MaxLength(255), Display(Name = "Description"), Required(AllowEmptyStrings = false)]
    public string Description { get; set; }

    [XmlIgnore, ScriptIgnore]
    public virtual List<Product> Products { get; set; }

    public InsuranceClass()
    {
        this.Products = new List<Product>();
    }

    //[Snip]
}

但我的产品表最终是这样的:

Products
Id
InsuranceClassId
ProductGroupId
InsuranceClass_Id
ProductGroup_Id

我做错了什么?它只发生在几张桌子上。

1 个答案:

答案 0 :(得分:0)

不是真正的答案,但上次发生这种情况时,我的映射错误,例如HasOptional(xx).WithMany();(缺少.HasForeignKey(xx))和EF约定在另一个xx_Id列中启动 - 也许你应该检查一下。