0

I am using ef core 2.1 in my application and trying to set up a relation between two entities as one-to-one relationship. At the same time i would like to keep foreign keys in both of my entities. Let's say classes are like:

class Principal
{
   int Id
   int PropA
   int PropB

   int DependentId
   virtual Dependent Dependent
}

class Dependent
{
   int Id
   int PropC
   int PropD

   int PrincipalId
   virtual Principal Principal
}

And with fluent api like:

builder.Entity<Principal>()
   .HasOne(a => a.Dependent)
   .WithOne(b => b.Principal)
   .HasForeignKey<Dependent>(c => c.PrincipalId);

In this scenario Dependent.PrincipalId is unique but Principal.DependentId is not. I would like both of them to be unique. Any idea how this can be achieved ?

Elnoor
  • 3,401
  • 4
  • 24
  • 39
  • just see this link https://stackoverflow.com/questions/51472764/change-many-to-one-relationship-into-one-to-one-ef/51473049#51473049 – Hossein Jul 24 '18 at 06:47
  • @Hossein how about having dependentId in principal class ? – Elnoor Jul 24 '18 at 06:54
  • Ok. see my answer. – Hossein Jul 24 '18 at 07:01
  • This is not supported by EF and in general is a bad db design. Why would you need 2 FKs and create circular relationship with all associated problems while a normal single FK is enough to represent such relationship? – Ivan Stoev Jul 24 '18 at 07:12
  • @IvanStoev Is it bad design ? Indeed i thought it may be good – Elnoor Jul 24 '18 at 07:16

1 Answers1

2

Mark one of the tables (the dependent table) with the ForeignKey attribute on its Primary Key. EF infers 1-to-1 from this:

class Principal
{
   int Id
   int PropA
   int PropB

   //int DependentId   ----> here
   virtual Dependent Dependent
}

class Dependent
{
   [ForeignKey("Principal")]
   int PrincipalId

   //int Id  ----> here
   int PropC
   int PropD

   virtual Principal Principal
}

and remove your fluent api

Hossein
  • 3,083
  • 3
  • 16
  • 33
  • didn't achieve what i was looking for, but anyways, i changed my mind doing what i was planning to do. Thank you. – Elnoor Jul 24 '18 at 07:22