The relationship could not be changed because one or more of the foreign-key properties is non-nullable on saving

c# entity-framework entity-framework-6 graphdiff

Accepted Answer

Most likely has to do with UserId not being nullable. As you are aware, EF writes User using UserId. EF cannot write the entity if User is null (it may be). It might also be connected to the user. EF's GroupId is used to map the Group. user data gathering.

I also don't comprehend your model. A User may belong to just one Group. There may be multiple Users in a Group.

If this is the case, why not just remove the association entity from your model to make it simpler? It is not necessary for EF.

public class Group
{
    public int Id { get; set; }
    public virtual ICollection<User> Users{ get; set; }
}

public class User
{
    public int Id { get; set; }
    public virtual Group Group { get; set; }
}

In this situation, all you need is UserMap.

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        // You don't need to set primary key. EF take Id and create an identity column
        //HasKey(t => t.Id); 

        // Table & Column Mappings
        ToTable("users");
        // No column mappings in this case.

        // Relationships
        HasRequired(t => t.Group)
            .WithMany(t => t.Users)
            .Map(d => d.MapKey("user_group"));

    }
}

If a User can belong to more than one Group, simply change your user model in this manner.

public class User
{
    public int Id { get; set; }
    public virtual ICollection<Group> Groups { get; set; }
}

Although you don't require the association object, EF recognizes that there is a many-to-many link and will construct the association table (UsersGroups).

EDIT

You seldom ever need to setdb.Entry(myEntity).State = EntityState.Modified; Proxies function well with EF6.

0
4/29/2016 6:15:26 AM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow