1

I am trying to figure out how to make this work in EF. I have two entities Employee and User. I need to make it so the User has an optional mapping to the Employee. If there is a mapping, then it would be 1:1.

Basically this system can be accessed by employees and also by outside vendors, but I want one table to manage logons: Users.

How do I define this realtionship in EF with fluid configurations?

Sam
  • 15,336
  • 25
  • 85
  • 148

2 Answers2

3

You just need to set simple fluent configuration:

modelBuilder.Entity<User>()
            .HasOptional(u => u.Employee)
            .WithRequired(e => e.User);

or in reverse order:

modelBuilder.Entity<Employee>()
            .HasRequired(e => e.User)
            .WithOptional(u => u.Employee);

EF will use Employess's PK as FK to user - that is mandatory requirement for EF to correctly use one-to-one relation. In case of Data annotation it is enough to mark Employee's PK with ForeignKey attribute pairing it with User navigation property:

public class Employee {
    [Key, ForeignKey("User")]
    public int Id { get; set; }

    public virtual User User { get; set; }
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • So is the fluent config above the same as the annotations? Also, when configuring a 1 - many relationship do I have to have a foreign key field and a navigation property? So in the case of the employee - user, do I have to have (on the employee) UserID and the nav property User? – Sam Aug 13 '12 at 03:33
  • Yes the fluent config is the same as the configuration with annotation. When configuring one to many relation you always have FK in the database but the existence of FK property in your class differs between [two possible types of associations](http://stackoverflow.com/questions/5281974/code-first-independent-associations-vs-foreign-key-associations/5282275#5282275) used in EF. – Ladislav Mrnka Aug 13 '12 at 08:14
1
public class User
{
    ...
    public virtual Employee Employee { get; set; }
}

This tutorial may help.

Garrett Fogerlie
  • 4,450
  • 3
  • 37
  • 56
  • so all you have to do is define a nullable type? When defining one to many relationships do you have to define a navigation property and a Fk? – Sam Aug 12 '12 at 07:16
  • This even doesn't compile because only value types can be made nullable. Reference types are nullable always and `Employee` is reference type. – Ladislav Mrnka Aug 12 '12 at 08:14