亲爱的程序员,
我在EF中坚持这个基本概念,无法在stackoverflow上找到任何解决方案。
我希望在FluxLocation和Address之间建立一对一的可选关系。 (正常词:通量位置可以提供物理地址)
请注意,数据库已存在并且是最终的。
SQL TABLES:
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 Mapping:
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()出错:
&#34; 42703:column \&#34; Address_Id \&#34; of&#34; sales_flux_location \&#34;不存在&#34;}
这是正确的,因为列名是&#34; sales_address_id&#34;。 如果任何人可以帮助他为什么忽略了有利的列名映射? 如果需要,我很乐意提供更多代码。
答案 0 :(得分:1)
EF没有提到你想要sales_address_id作为FK,所以它试图创建Address_Id。此外,EF有0:1
的方式有些奇怪 - 基本上你需要用1:M
所以试试这个:
//FK
HasOptional(l => l.Address)
.WithMany()
.HasForeignKey(d => d.AddressId);