亲爱的其他程序员,
我将这个基本概念粘在EF中,无法在stackoverflow上找到任何解决方案。
我想在以下位置之间建立一对一的可选关系:FluxLocation和Address。(普通单词:可以提供一个物理地址的通量位置)
注意数据库已经存在,并且最终。
SQL表:
CREATE TABLE sales.sales_flux_location(
id serial PRIMARY KEY,
-- Many unusefull properties
sales_address_id integer REFERENCES sales_address
);
CREATE TABLE sales.sales_address(
id serial PRIMARY KEY,
-- Many unusefull properties
);
ef映射:
public partial class FluxLocation
{
public int Id { get; set; }
//Many unusefull properties.
[ForeignKey("Address")]
public int? AddressId { get; set; }
public Address Address { get; set; }
}
internal partial class FluxLocationConfiguration : EntityTypeConfiguration<FluxLocation>
{
public FluxLocationConfiguration()
{
//PK
HasKey(x => x.Id);
ToTable("sales_flux_location", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(l => l.Address)
.WithOptionalDependent(a => a.FluxLocation);
Property(l => l.AddressId)
.HasColumnName("sales_address_id")
.IsOptional();
// + mapping other properties.
}
public partial class Address
{
public int Id { get; set; }
// other properties
public FluxLocation FluxLocation { get; set; }
}
internal partial class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
//PK
HasKey(a => a.Id);
ToTable("sales_address", "sales");
Property(a => a.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//FK
HasOptional(a => a.FluxLocation).WithOptionalPrincipal(l=>l.Address);
// mapping many unusefull properties
}
测试案例:
var dbAddress = Context.AddressSet.Add(new Address {Country = "BEL", CityName="Brussel", Street = Guid.NewGuid().ToString() });
var dbLocation = Context.FluxLocationSet.Add(new FluxLocation { AddressId = dbAddress.Id, Country = "BEL", Type = "MARKET", ExtId = Guid.NewGuid().ToString() });
Context.SaveChanges();
context.savechanges上的错误():
" 42703:column " address_id " of关系" sales_flux_location "不存在"}
这是正确的,因为列名是" sales_address_id"。如果有人可以帮助他为什么忽略Propery columnname映射?我很乐意在需要时提供更多代码。
ef并未接收您希望sales_address_id作为FK,因此它尝试创建address_id。另外,EF如何执行0:1
也有一些奇怪的事物 - 本质上,您需要用1:M
所以尝试一下:
//FK
HasOptional(l => l.Address)
.WithMany()
.HasForeignKey(d => d.AddressId);
链接