在实体框架6中更新多对多关系的问题(代码优先) [英] Problems with updating many-to-many relationships in Entity Framework 6 (Code First)

查看:75
本文介绍了在实体框架6中更新多对多关系的问题(代码优先)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表格设置

 用户
- Id
- 名称

角色
- Id
- 名称

UserRole
- UserId
- RoleId
/ pre>

使用流利我已经声明了以下关系:

  .HasMany(t => t.Roles)
.WithMany(s => s.Users)
.Map(m =>
{
m.ToTable UserRole);
m.MapLeftKey(UserId);
m.MapRightKey(RoleId);
});

当我创建一个具有多个角色的新用户时,它会在数据库中正确添加它们。
当我更新一个尚不存在的角色的用户,那么这是可以的。



我在添加以下内容时遇到问题:



现有角色

 角色A 
角色B
角色C

我想删除角色B,因此离开

 角色A 
角色C

已经尝试了几件事情,但我总是最终得到附加信息:保存或接受更改失败,因为多个类型...角色的实体具有相同的主键值。或者根本没有删除。



方法1



我已经尝试过创建一个方法来删除所有角色首先只是添加传入角色,但由于某些原因,它会维护跟踪的更改,并且仍然会看到已删除的角色。

  public ActionResult Edit(int userId,User user)
{
//清除角色
_userService.ClearRoles(userId);
_unitOfWork.Save();

//如果我在这里休息一下,我可以看到从数据库中删除的角色


//更新用户新角色
_userService.Update(id,user)
_unitOfWork.Save();

}


// _userService.Update

public void Update(int userId,User user)
{
用户existingUser = Find(userId);
if(existingUser!= null)
{
existingUser.Roles = user.Roles;
_userRepository.Update(existingUser);
}
}

public void ClearRoles(int userId)
{
User existingUser = GetUser(userId);

if(existingUser!= null)
{
existingUser.Roles.ToList()。ForEach(f => existingUser.Roles.Remove(f));
}
}

方法2



我尝试删除角色对象,但没有角色被删除,没有任何事情

  public ActionResult Edit userId,User user)
{
_userService.Update(id,user)
_unitOfWork.Save();

}


// _userService.Update

public void Update(int userId,User user)
{
用户existingUser = Find(userId);

if(existingUser!= null)
{
existingUser.Roles.ToList()。ForEach(f => existingUser.Roles.Remove(f));
existingUser.Roles = user.Roles;

_userRepository.Update(existingUser);
}
}

有关如何解决这个问题的进一步想法? p>

解决方案


关于错误:保存或接受更改失败,因为
超过一个实体类型具有相同的主键值...


通常发生在dbcontext,具有多个相同对象不同的数据库上下文中,被刷新到数据库。



示例

  public void Save(PlcVariable plcVariable)
{
try
{
using(var context = new XBSDbDataContext())
{
plcVariable.PlcVariableMeasure.LineObjects // Plc变量具有一个具有lineobject列表的自引用,它已经有一个行对象,id = 1
var lineobject = new LineObjectService()。 GetById(1); // =>这个线对象是从另一个Dbcontext生成的。
plcVariable.LineObjects.Add(lineobject);
context.SaveChanges(); //发生错误
// EF会将添加的行对象视为不同的对象,因为它来自另一个dbcontext,而不是与已存在的相同对象(等于id)。
}

您可以尝试使用一个dbContext来加载对象。


I have a simple table setup

User
- Id
- Name

Role
- Id
- Name

UserRole
- UserId
- RoleId

Using Fluent I have the following relationship declared

this.HasMany(t => t.Roles)
.WithMany(s => s.Users)
.Map(m =>
{
        m.ToTable("UserRole");
        m.MapLeftKey("UserId");
        m.MapRightKey("RoleId");
});

When I create a new User with multiple Role it adds them correctly in the Database. When I Update a User with Role's that don't already exist yet then it is OK.

I am having problems adding the following:

Existing Roles

Role A
Role B
Role C

I want to remove Role B thus leaving

Role A
Role C

I have tried a couple of things but I always end up with the "Additional information: Saving or accepting changes failed because more than one entity of type '...Role' have the same primary key value." or no deletion occurs at all.

Method 1

I have tried things like creating a method to delete all the Roles first then just adding the incoming Roles but for some reason it's maintaining the tracked changes and still sees the Roles that are deleted.

public ActionResult Edit(int userId, User user)
{
    // clear roles
    _userService.ClearRoles(userId);
    _unitOfWork.Save();

    // if I put a break here, I can see the roles being removed from the database


    // update user with new roles
    _userService.Update(id, user)
    _unitOfWork.Save();

}


// _userService.Update

public void Update(int userId, User user)
{
    User existingUser = Find(userId);
    if (existingUser != null)
    {
        existingUser.Roles = user.Roles;
        _userRepository.Update(existingUser);
    }
}

public void ClearRoles(int userId)
{
   User existingUser = GetUser(userId);

   if(existingUser != null)
   {
       existingUser.Roles.ToList().ForEach(f => existingUser.Roles.Remove(f));                
   }
}

Method 2

I tried to remove the Role objects but no Roles get deleted, nothing happens

 public ActionResult Edit(int userId, User user)
 {
        _userService.Update(id, user)
        _unitOfWork.Save();

 }


// _userService.Update

public void Update(int userId, User user)
{
    User existingUser = Find(userId);

    if (existingUser != null)
    {
        existingUser.Roles.ToList().ForEach(f => existingUser.Roles.Remove(f));
        existingUser.Roles = user.Roles;

        _userRepository.Update(existingUser);
    }
}

Any further ideas on how to resolve this?

解决方案

Concering the error: "Saving or accepting changes failed because more than one entity of type '' have the same primary key value"...

This often occurs when a dbcontext, having several same objects orginated from a different db context, is flushed towards the database.

Example

  public void Save(PlcVariable plcVariable)
    {
        try
        {
            using (var context = new XBSDbDataContext())
            {
                plcVariable.PlcVariableMeasure.LineObjects // Plc variable has a selfreference that has a list of lineobject, that already has a line object with id = 1
                var lineobject =  new LineObjectService().GetById(1);//=> this line object is orginated from another Dbcontext.
                plcVariable.LineObjects.Add(lineobject); 
                context.SaveChanges(); // error occurs
                // EF will see the added line object as a different object, because it is coming from another dbcontext, than the same object(equal id's) that is already present.
            }

You can try to assure to load object with one dbContext.

这篇关于在实体框架6中更新多对多关系的问题(代码优先)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆