Mathieu
Mathieu

Reputation: 4520

EF relationship adds new record instead of linking

I know you'll tell me this has been asked before. Maybe I don't search correctly, but I don't find the answer.

var userRepo = new UserRepository();
var user = new User {Name = "Bob"};
userRepo.Save(user);

var roleRepo = new RoleRepository();
var role = new Role {Name = "My role"};
roleRepo.Save(role);

user.Roles.Add(role); //I expect this to link user to role, but it adds a second role
userRepo.Save(user);

Maybe the problem is in my repository, but I doubt:

public void Save(Role role)
{
    if (role.ID == 0)
         context.Roles.Add(role);
    else
    {
         var currentRole = context.Roles.Find(role.ID);
         context.Entry(currentRole).CurrentValues.SetValues(role);
    }
    context.SaveChanges();

 }

Upvotes: 0

Views: 40

Answers (1)

Mathieu
Mathieu

Reputation: 4520

As Colin pointed out, it is a Context issue. The UserRepository was not aware of the new Role that was inserted in the db.

Upvotes: 1

Related Questions