EF code first - configure One-to-Zero-or-One relationship without shared PK/FK

后端 未结 1 1379
心在旅途
心在旅途 2021-01-22 09:06

I am trying to establish a One-to-Zero-or-One relationship between two entities and I want the dependent entity to still contain its own Indentity column, instead of it being a

1条回答
  •  离开以前
    2021-01-22 09:39

    Bidirectional one-to-one relationship with explicit FK property is not supported.

    So either continue using what you have now - Shared Primary Key association. Just get rid of one of the TaskId or FileId properties from Task and make the remaining a PK (EF will automatically use it as FK because that's the default EF one-to-one relationship model).

    Or get rid of the FieldId property from Task and use the following fluent configuration (all is necessary):

    modelBuilder.Entity()
        .HasOptional(f => f.Task)
        .WithRequired(t => t.File)
        .Map(m => m.MapKey("FileId"))
        .WillCascadeOnDelete();
    

    But I would recommend using the first approach (if there is no special reason of not doing it like existing database etc.) because it's better supported - the second includes some LEFT OUTER JOINs in SQL queries as you can see from this post EF - WithOptional - Left Outer Join?.

    0 讨论(0)
提交回复
热议问题