0

How to implement 1:1 relations without link in one entity?

public class Foo
{
    public int Id { get; set; }
    ...
}
public class Bar
{
    public int Id { get; set; }
    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }
    ...
}

Fluent API:

Entity<Bar>.HasKey(bar => bar.FooId)
    .HasRequired(bar=> bar.Foo)
    .WithMany()
    .HasForeignKey(p => p.FooId)
    .WillCascadeOnDelete(false);

And its create one to many in db

kenazs
  • 71
  • 10
  • See https://stackoverflow.com/questions/43053021/how-do-i-specify-the-foreign-key-in-a-one-to-one-zero-relationship/43053532#43053532 – Ivan Stoev Jun 27 '19 at 06:42
  • 1
    Possible duplicate of [One to one optional relationship using Entity Framework Fluent API](https://stackoverflow.com/questions/18240362/one-to-one-optional-relationship-using-entity-framework-fluent-api) – Mustafa Gursel Jun 27 '19 at 06:43
  • @IvanStoev I need to use it without inheritance – kenazs Jun 27 '19 at 07:15
  • It has nothing to do with inheritance. The key point in the linked answer is that you have to remove `FooId` property from `Bar`. And use either `Id` as both PK and FK (preferred), or configure shadow FK. In both cases you need `.HasRequired(bar=> bar.Foo).WithOptional()`. The best explanation for me is [here](https://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations) (included in the other link). – Ivan Stoev Jun 27 '19 at 07:20
  • @IvanStoev thanks. This article helps me. Its normal that I should mark that ``FooId`` is primary key? Why fluent doesn't create it by itself when ``.HasRequired(bar=> bar.Foo).WithOptional()``? in the examples in the article, the primary key was not assigned – kenazs Jun 28 '19 at 04:07

0 Answers0