我试图使用单个地址表来存储系统中具有通用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);
希望它会有所帮助.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。