entity-frameworkmappingef-code-firstforeign-key-relationshipentity-framework-4.1

Entity framework code-first null foreign key


I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).

How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.

The model is as follows:

 public class User{
    public int CountryId { get; set; }
    public Country Country { get; set; }
}

public class Country{
    public List<User> Users {get; set;}
    public int CountryId {get; set;}
}

Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}


Solution

  • You must make your foreign key nullable:

    public class User
    {
        public int Id { get; set; }
        public int? CountryId { get; set; }
        public virtual Country Country { get; set; }
    }