首页 新闻 赞助 找找看

asp.net mvc EF保存问题?

0
悬赏园豆:30 [已解决问题] 解决于 2015-12-01 10:17

项目中更新一张表,数据有新增的也有修改的,代码如下:

//新增

db.Order.AddRange(newOrderList);

//修改

db.Order.Attach(order);
db.Entry(order).State = System.Data.Entity.EntityState.Modified;

在“db.Order.Attach(order);”这句代码抛异常,异常信息如下:

Attaching an entity of type 'Model.Order' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

说我的实体主键重复,我检查过了,主键不重复,无论新增的还是修改的数据均不重复。请问这里我该怎么写呢?

横槊的主页 横槊 | 初学一级 | 园豆:12
提问于:2015-11-30 11:22
< >
分享
最佳答案
0

你在Attach 的时候,EF对实体状态维护的上下文中已经存在了改主键的对象。

db.Order.Loacl.xxxx  可以用这个时候验证下 是不是已经在追踪状态了

 

直接更新实体,或插入实体,可以参考下 下面这个博文对于更新的实现方式

http://www.cnblogs.com/guomingfeng/p/mvc-ef-update.html

收获园豆:30
Sky.Grain | 菜鸟二级 |园豆:308 | 2015-11-30 13:18
其他回答(1)
0

//4,更新到数据库
  db.SaveChanges();
//5,更新成功,则命令流浪器重定向 到 /Home/Index 方法

return RedirectToAction("Index", "Home");

 

你可以进行试一下。我以前就是这样解决的

LowKeyC | 园豆:87 (初学一级) | 2015-11-30 11:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册