我知道你会告诉我这已经被问过了。也许我没有正确搜索,但我没有找到答案。
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);
也许问题出在我的存储库中,但我怀疑:
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();
}