流利的API生产重复列
问题描述:
我们正试图让我们用流利的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]
解决他们,但我是新来的流畅API和不确定我做错了这里。我如何在Fluent中解决这个问题,以便正确地获取我的导航属性/外键?
答
原来的问题是在映射配置为CustomerModel
,有一次我清理,高达,我的问题就走了:
HasMany(x => x.Locations)
.WithRequired(x => x.Customer)
.HasForeignKey(x => x.CustomerId);