Search code examples
c#entity-frameworkentity-relationshipentities

How to change EF CodeFirst multiplicity from one to zero/one?


Imagine I have two entities:

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

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

If I try to add a user who doesn't belong to any country, I get an UpdateException on the SaveChanges command:

Entities in 'SLContext.User' participate in the 'Country_Users' relationship. 0 related 'Country_Users_Source' were found. 1 'Country_Users_Source' is expected

I believe this issue is related to the autogenerated one-to-many relationship. How can I set this multiplicity to 0.1 ---> * ?


Solution

  • If you are using FluentAPI, configuration for User Entity should be :

       HasOptional(x=> x.Country)
           .WithMany(x=> x.Users);
    

    And your User Entity :

       public class User{
            public Guid UserId { get; set; }
            public virtual Country Country { get; set; }
       }
    

    Hope this help.