How to get Entity Framework Code First and nullabl

2020-02-08 08:55发布

问题:

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?

回答1:

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.



回答2:

@b3n It should be enough to do this, at least with VS 2013:

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

   public string Username { get; set; }

   public int? ActivationTicketId { get; set;}

   public virtual ActivationTicket ActivationTicket { get; set; }
}

This is the important part:

public int? ActivationTicketId { get; set;}

This will specify the foreignkey in your "User" table for the ActivasionTicket and define that it's optional.

credits go to: http://forums.asp.net/t/1948351.aspx?Change+Foreign+Key+to+nullable+using+Code+First#5554732

I had the same problem and it instantly worked for me.

Also as a note i marked all my primary keys with the data annotation "[Key]". This might be necessary in order to make this work.