实体框架:实体对象不能被IEntityChangeTracker的多个实例引用 [英] Entity Framework: An entity object cannot be referenced by multiple instances of IEntityChangeTracker

查看:198
本文介绍了实体框架:实体对象不能被IEntityChangeTracker的多个实例引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户表,与一个警报表有多对多的关系。创建成员资格用户后,我在数据库中添加了一些额外的信息。

  MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName ,model.Password,model.Email); 

if(createStatus == MembershipCreateStatus.Success){
User user = new MidTier.Models.User();
user.FullName = model.FullName;
if(Alerts.Count()> 0)
{
var userAlerts = SetAlert(Alerts); //创建一个IEnumerable的警报(从int列表)
foreach(userAlerts中的var alert)
{
user.Alerts.Add(alert); //向用户添加每个警报
}
}
userRepository.Add(user); //抛出错误
userRepository.Save();
}

我收到错误('一个实体对象不能被引用调用Add方法时,IEntityChangeTracker的多个实例。')。有很多关于这个错误在网上甚至在这里SO的参考,但在阅读所有这些意见和建议后,我没有找到一个解决方案或原因我得到这个错误。

解决方案


有很多关于
的参考,这个错误在网上甚至这里SO,
,但阅读全部后那些评论
和建议,我havent找到一个
解决方案或原因我得到
这个错误。


如果你真的搜索,你应该已经知道错误说你的对象图中的一些实体已经附加到其他上下文。因为你的代码示例大多没有关系。真正的重要代码包含在您的方法中 - 可能 SetAlerts userRepository.Add 。如果这两种方法使用内部上下文,并且它们不使用相同的实例,则是您的异常的原因。


I have a User table, with a many-to-many relationship to an Alerts table. After creating a Membership user, I am adding some extra info into the database.

MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

if (createStatus == MembershipCreateStatus.Success)   {
User user = new MidTier.Models.User();
user.FullName = model.FullName;
if (Alerts.Count() > 0)
  {
    var userAlerts = SetAlert(Alerts); // creates an IEnumerable of Alerts (from a list of int )
    foreach (var alert in userAlerts)
         {
            user.Alerts.Add(alert);                  //add each alert to the user
          }                    
   }
   userRepository.Add(user); //throwing error
   userRepository.Save();
}

I get an error (' An entity object cannot be referenced by multiple instances of IEntityChangeTracker.') on calling the Add method. there are lots of references about this error on the net even here on SO, but after reading all those comments and suggestions, I a havent found a solution or the reason I am getting this error.

解决方案

there are lots of references about this error on the net even here on SO, but after reading all those comments and suggestions, I a havent found a solution or the reason I am getting this error.

If you really searched you should already know that error says you that some entity in object graph is already attached to other context. Because of that your code sample is mostly not related. The real important code is wrapped in your methods - probably SetAlerts and userRepository.Add. If these two methods use internally context and they don't use the same instance it is the reason for your exception.

这篇关于实体框架:实体对象不能被IEntityChangeTracker的多个实例引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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