一对一数据库优先 EF

One-To-one Database First EF

亲爱的程序员们,

我坚持使用 EF 中的这个基本概念,在 Whosebug 上找不到任何解决方案。

我想在 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 relation \"sales_flux_location\" does not exist"}

这是正确的,因为列名是 "sales_address_id"。 如果有人可以帮助他为什么忽略 属性 列名映射? 如果需要,我很乐意提供更多代码。

EF 没有选择您想要 sales_address_id 作为 FK,因此它尝试创建 Address_Id。此外,EF 0:1 的工作方式有些奇怪 - 本质上你需要用 1:M

来愚弄它

所以试试这个:

//FK
HasOptional(l => l.Address)
    .WithMany()
    .HasForeignKey(d => d.AddressId);

Link