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

前端 未结 2 573
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 11:24

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

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

    pu         


        
相关标签:
2条回答
  • 2020-12-14 12:26

    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.

    0 讨论(0)
  • 2020-12-14 12:26

    @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.

    0 讨论(0)
提交回复
热议问题