143

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 ]"}

3
  • Can you kindly correct me if i am wrong. A foreign key is NULLABLE by DEFAULT in code first asp.net mvc - 5 entity framework. Commented Aug 9, 2017 at 22:34
  • 1
    If we want to make it non nullable. we need to either use fluent api if not then decorate with "Required" attribute. Am I correct? Commented Aug 9, 2017 at 22:34
  • 2
    If we don't do either then Foreign key will be defaulted to Nullable Commented Aug 9, 2017 at 22:35

5 Answers 5

218

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; }
}
Sign up to request clarification or add additional context in comments.

12 Comments

Virtual is necessary for lazy loading.
Virtual also adds change tracking, which isn't always wanted. About the only time that we ever want virtual is on collections, but YMMV.
@LadislavMrnka - And how would the lazy loading work when an attempt to get a navigation property was made when the id was null (which throws an exception)?
@TravisJ user.Country returns null then... either catch the exception (optimal) or use if (eww)
Also -- this doesn't seem to work for Guid based keys. (It makes them nullable, sure, but saving a record to the database with the foreign key set to null fails due to an automatically generated foreign key constraint.) :-(
|
15

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

1 Comment

This is exactly the problem I was having. I don't even have a navigation property in my entity, so it's a bit odd that it's happening anyway.
9

I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

in DBContext class I am sorry for answer you very late :)

1 Comment

'WithOptional' no linger valid for EFCore... only has 'WithOne'
5

In EF 7 :

entity.Property(e => e.propertyName).IsRequired(false);

Comments

0

I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.

enter image description here

Guide link below:

https://learn.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.