实体框架:实体对象不能被 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); // 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();
}
调用 Add 方法时出现错误(“IEntityChangeTracker 的多个实例无法引用实体对象。”)。即使在网上,网上也有很多关于此错误的参考资料,但在阅读了所有这些评论和建议后,我还没有找到解决方案或出现此错误的原因。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实进行了搜索,您应该已经知道该错误表明对象图中的某些实体已经附加到其他上下文。因此,您的代码示例大多不相关。真正重要的代码包含在您的方法中 - 可能是
SetAlerts
和userRepository.Add
。如果这两个方法使用内部上下文并且它们不使用相同的实例,那么这就是异常的原因。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
anduserRepository.Add
. If these two methods use internally context and they don't use the same instance it is the reason for your exception.