Search code examples
c#.netentity-framework-4ef-code-first

How to get Entity Framework Code First and nullable foreign key properties to work?


I'm trying to create a simple entity framework code first application. I have these classes:

public class User
{
    public int UserId { get; set; }

    public string Username { get; set; }

    public virtual ActivationTicket ActivationTicket { get; set; }
}

public class ActivationTicket
{
    public int ActivationTicketId { get; set; }

    public virtual User User { get; set; }

    public string Ticket { get; set; }
}

When I try to create a new user and save it to the database (a user without a ActivationTicket that is) I receive an exception

The INSERT statement conflicted with the FOREIGN KEY constraint "ActivationTicket_User". The conflict occurred in database "Test", table "dbo.ActivatioTickets", column 'ActivationTicketId'. The statement has been terminated.

I assume EF treats the mapping between User and ActivationTicket as 1-1 but it should be 1-0..1

What do I have to do to get this to work?


Solution

  • You will need a mapping rule like this:

    modelBuilder
        .Entity<User>()
        .HasOptional<ActivationTicket>(u => u.ActivationTicket)
        .WithOptionalPrincipal();
    

    This will give you an ActivationTickets table with a UserId that is nullable.