Fluent API生成重复列

时间:2017-10-05 02:19:47

标签: c# entity-framework entity-framework-6 ef-fluent-api

我们正在尝试重新配置我们的EF项目,以便我们使用流畅的API配置而不是数据注释来获得更清晰的数据模型。我们现有表格,现在我正试图验证我的努力。

以下是旧的(部分)EF模型声明:

[Table("CustomerLocation")]
internal class CustomerLocationEF
{
    [Column(Order = 0), Key]
    public int CustomerID { get; set; }

    [Column(Order = 1), Key]
    [Required]
    [MaxLength(ModelConstants.MaxLength128)]
    [Index("IX_Customer_LocationReference", IsUnique = true)]
    public string LocationReference { get; set; }

    public virtual CustomerEF Customer { get; set; }
}
[Table("Customer")]
internal class CustomerEF
{
    [Key]
    public int CustomerID { get; set; }

    public virtual ICollection<CustomerLocationEF> Locations { get; set; }
}

这些工作正常并产生预期的架构。但是,以下是新型号和配置:

public class CustomerLocationModel
{
    public int CustomerId { get; set; }

    public string LocationReference { get; set; }

    public virtual CustomerModel Customer { get; set; }
}
public class CustomerModel
{
    public int Id { get; set; }

    public virtual ICollection<CustomerLocationModel> Locations { get; set; }
}

internal sealed class CustomerLocationTypeConfiguration : EntityTypeConfiguration<CustomerLocationModel>
{
    public CustomerLocationTypeConfiguration()
    {
        ToTable("CustomerLocation");

        HasKey(x => new {x.CustomerId, x.LocationReference});

        Property(x => x.CustomerId)
            .HasColumnName("CustomerID");

        HasRequired(x => x.Customer).WithMany().WillCascadeOnDelete(false);
    }
}

但是,这会尝试生成如下表:

CreateTable(
        "dbo.CustomerLocation",
        c => new
            {
                CustomerID = c.Int(nullable: false),
                LocationReference = c.String(nullable: false, maxLength: 128),
                CustomerModel_Id = c.Int(),
            })
        .PrimaryKey(t => new { t.CustomerID, t.LocationReference })
        .ForeignKey("dbo.Customer", t => t.CustomerID)
        .ForeignKey("dbo.Customer", t => t.CustomerModel_Id)
        .Index(t => new { t.CustomerID, t.LocationReference }, unique: true, name: "IX_Customer_LocationReference")
        .Index(t => t.CustomerModel_Id);

请注意重复列CustomerModel_Id和关联的外键。我之前使用数据注释遇到了类似的问题,并使用[ForeignKey]解决了这些问题,但我是Fluent API的新手,并且不确定我在这里做错了什么。如何在Fluent中解决此问题,以便它正确地获取我的导航属性/外键?

1 个答案:

答案 0 :(得分:0)

事实证明问题出现在CustomerModel的映射配置中,一旦我清理完了,我的问题就消失了:

HasMany(x => x.Locations)
                .WithRequired(x => x.Customer)
                .HasForeignKey(x => x.CustomerId);