0

I have 2 models which must be one to one relation

public class Reference
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class Matrix
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int ReferenceId {get;set;}
    public Reference Reference {get;set; }
}

One Matrix can only have one Reference and One Reference can only have one Matrix

Here is the problem, the Reference can exist without a Matrix, ReferenceId must be unique on the Matrix

How can i do this besides making the foreign key nullable but still unique?

Jackal
  • 3,359
  • 4
  • 33
  • 78
  • 1
    Make it nullable and add a UniqueIndex? Look here if you are using SQL Server: https://stackoverflow.com/questions/767657/how-do-i-create-a-unique-constraint-that-also-allows-nulls/767702#767702 – Camilo Terevinto Jun 25 '19 at 11:58
  • Yes but i am using Entity Framework Core – Jackal Jun 25 '19 at 12:00
  • 1
    So...? How does that matter? You can configure that through EF Core as long as your database allows that – Camilo Terevinto Jun 25 '19 at 12:01
  • 1
    *"Reference can exist without a Matrix"* This doesn't require changing the model. Nullable FK will be needed if "Matrix can exist without a Reference". – Ivan Stoev Jun 25 '19 at 12:12
  • Ah i understand thanks. I i think i just need an unique index on Matrix since it cannot exist without a Reference – Jackal Jun 25 '19 at 12:28
  • Just configure [one-to-one relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships#one-to-one). EF Core will add unique index automatically for you (in case you are using migrations). – Ivan Stoev Jun 25 '19 at 14:21

0 Answers0