c# – 单个地址表,用于存储具有Entity Framework的许多实体(使用双外键)的地址

我试图使用单个地址表来存储系统中具有通用KeyId字段的多个实体的地址.客户可以拥有多个地址,供应商可以拥有多个地址.

地址类:

public int Id { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
// These 2 fields make it so I can get all of the addresses for a single Customer or Vendor
public string EntityType { get; set; }
public int KeyId { get; set; }

// Navigation properties
public Customer Customer { get; set; }
public Vendor Vendor { get; set; }
public Location Location { get; set; }

客户类:

public int Id { get; set; }
public string Name { get; set; }

// Navigation properties
public IList<Address> Addresses { get; set; }

供应商类别:

public int Id { get; set; }
public string Name { get; set; }

// Navigation properties
public IList<Address> Addresses { get; set; }

的DbContext:

    builder.Entity<Customer>()
        .HasMany(c => c.Addresses)
        .WithOne(a => a.Customer)
        .HasForeignKey(a => a.KeyId);

    builder.Entity<Vendor>()
        .HasMany(v => v.Addresses)
        .WithOne(a => a.Vendor)
        .HasForeignKey(a => a.KeyId);

在尝试为数据库设定种子时(添加一个供应商和一些地址)我遇到了一个错误,说明如下:

SqlException: The MERGE statement conflicted with the FOREIGN KEY constraint “FK_Address_Customer_KeyId”. The conflict occurred in database “MyDatabase”, table “dbo.Customer”, column ‘Id’.

我很确定这是因为引用完整性,说数据库中没有客户,而您正在尝试将其存储在KeyId中.

有没有办法用F / FluentAPI做这样的事情,或者我玩火?如果所有属性都相同,那么创建名为CustomerAddress和VendorAddress的类似乎太疯狂了.这几乎就像我需要指定EF不允许你做的双外键.

附加说明:我想我将尝试在SQL管理工作室中设置所有内容,然后在Visual Studio中添加数据库第一个EF项目.我很想知道如何创建模型和数据库上下文.

最佳答案 看起来客户/供应商与地址类之间的映射不正确.

您应该在Address表中有不同的ForeignKey列指向不同的父表[Customer / Vendor].

因此,在更改之后,您的实体将如下所示:

地址:

 public int Id { get; set; }
 public string Name { get; set; }
 public string Address1 { get; set; }
 public string Address2 { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public string Country { get; set; }
 public string ZipCode { get; set; }
 public int CustomerId { get; set; }
 public int VendorId { get; set; }


 // Navigation properties
 public Customer Customer { get; set; }
 public Vendor Vendor { get; set; }

的DbContext:

builder.Entity<Customer>()
    .HasMany(c => c.Addresses)
    .WithOne(a => a.Customer)
    .HasForeignKey(a => a.CustomerId);

builder.Entity<Vendor>()
    .HasMany(v => v.Addresses)
    .WithOne(a => a.Vendor)
    .HasForeignKey(a => a.VendorId);

希望它会有所帮助.

点赞