【问题标题】:Duplicate navigation properties when using Entity Framework 6 and fluent api使用 Entity Framework 6 和 fluent api 时出现重复的导航属性
【发布时间】:2013-11-08 16:47:05
【问题描述】:

我有两个有关系的模型。

public class Customer
{
    public Customer()
    {
        CustomerSites = new List<CustomerSite>();
    }     

    public IList<CustomerSite> CustomerSites { get; set; }
}

public class CustomerSite
{
    public Guid CustomerId { get; set; }
    public Customer Customer { get; set; }
}

关系是由fluent api建立的:(我也尝试过仅使用以下语句之一)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<CustomerSite>()
            .HasRequired(x => x.Customer)
            .WithMany(x => x.CustomerSites)
            .HasForeignKey(x => x.CustomerId);

        modelBuilder.Entity<Customer>()
            .HasMany(x => x.CustomerSites)
            .WithRequired(x => x.Customer)
            .HasForeignKey(x => x.CustomerId);
}

我的问题是为什么这段代码会生成数据库的双外键,如下例所示。

 "dbo.CustomerSites",
            c => new
                {                     
                    CustomerId = c.Guid(nullable: false),                     
                    Customer_Id = c.Guid(),
                })
            .ForeignKey("dbo.Customers", t => t.CustomerId, cascadeDelete: true)
            .ForeignKey("dbo.Customers", t => t.Customer_Id)

它应该只有一个 CustomerId 而不是 Customer_Id。如您所见,这也是可以为空的。如果我在 db 上下文中删除此列,则会在更新时引发异常。我觉得这很奇怪....

【问题讨论】:

  • 这是错误还是功能?

标签: c# entity-framework foreign-keys fluent entity-framework-6


【解决方案1】:

原因是在重构过程中,实体中留下了一些旧属性,这些属性在自动映射到数据库中的其他 FK 时受到影响。

例子:如果我们有

public class CustomerSite
{
    public Guid CustomerId { get; set; }
    public Customer Customer { get; set; }
    ............
    public Customer Customer1 { get; set; }
}

并且只有一个流畅的映射语句,如

modelBuilder.Entity<CustomerSite>().HasRequired(x => x.Customer)
.WithMany(x => x.CustomerSites).HasForeignKey(x => x.CustomerId);

在数据库中,我们将有额外的 FK,例如 Customer1_Id,它可以为空。

注意。可能对某人有帮助!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2015-03-29
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多