One to one optional relationship using Entity Framework Code First

Here’s an example from the Programming E.F. Code First book

modelBuilder.Entity<PersonPhoto>()
.HasRequired(p => p.PhotoOf)
.WithOptional(p => p.Photo);
The PersonPhoto entity has a navigation property called PhotoOf (that points to a Person type). the Person type has a navigation property called Photo that points to the PersonPhoto type.

In the two related classes, you use each types KEY, not foreign keys. I.E. you won’t use the LoyaltyUserDetailId or PIIUserId properties. Instead, the relationship depends on the Id fields of both types.

If you are using the fluent API as above, you do not need to also specify LoyaltyUser.Id as a FK, EF will figure it out.

So without having your code to test myself (I hate doing this from my head)…I would translate this into your code as

public class PIIUser
{
    public int Id { get; set; }   
    public LoyaltyUserDetail LoyaltyUserDetail { get; set; }
}

public class LoyaltyUserDetail
{
    public int Id { get; set; }
    public double? AvailablePoints { get; set; }   
    public PIIUser PIIUser { get; set; }
}

modelBuilder.Entity<LoyaltyUserDetail>()
.HasRequired(lu => lu.PIIUser )
.WithOptional(pi => pi.LoyaltyUserDetail );
That’s saying LoyaltyUserDetails PIIUser property is required and PIIUser’s LoyaltyUserDetail property is optional.

You could start from the other end:

modelBuilder.Entity<PIIUser >()
.HasOptional(pi => pi.LoyaltyUserDetail );
.WithRequired(lu => lu.PIIUser);
which now says PIIUser’s LoyaltyUserDetail property is optional and LoyaltyUser’s PIIUser property is required.

You always have to use the pattern HAS/WITH.

other example:
One solution would be;

public class User
{
    [Key]
    public string Username { get; set; }

    public virtual Contact Contact { get; set; }
}

public class Contact
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual User User { get; set; }
}

        modelBuilder.Entity<User>()
            .HasOptional<Contact>(u => u.Contact)
            .WithOptionalDependent(c => c.User).Map(p => p.MapKey(“ContactID”));

one to one (or one to zero/one) relationships are one of the most confusing relationships to configure in code first so you are not alone..:)