Search code examples
c#entity-frameworkentity-framework-6.1ef-fluent-api

How to configure one to one optional relationship with FK


For a restriction of our architecture, the Id property can not be changed!

I have an employee class:

public class Employee 
{
    public virtual int Id {get; Set; } 
    public virtual int Matricula {get; Set; } 
}

And a user class (System User)

public class User 
{
    public virtual int Id {get; Set; } 
    public virtual int Matricula {get; Set; } 
    public virtual Employee Employee {get; Set; } 
} 

The Matricula property in User class should be a FK pointing to the class Employee with the Matricula property.

The Employee property in User class represents the Employee object associated with the same Matricula.

How do I set this via Fluent API in EF?

The goal is that, if the Matricula in employee is the same of Matricula property in user, they must be associated and Employee class will be filled with this employee in User class.


Solution

  • Unfortunately it's not possible to do using EF. For One-to-one relationship Matricula have yo be PRIMARY KEY in both entities.