2017-05-04 35 views
0

我写了这个代码在控制器:我得到商店更新,插入或删除语句受影响的行意想不到数(0)错误

public ActionResult AddNotice(NoticeViewModel nVN) 
    { 
     BOL.User CurrentUser = userbs.user.GetUser(User.Identity.Name); 
     int UserId = CurrentUser.ID; 

     var objNotice = new BOL.Notice() 
     { 
      NoticeID = nVN.SelectedNoticeTypeId, 
      ProductID = nVN.ProductID, 
      UserID = UserId 
     }; 
     objBs.notice.AddNotice(objNotice); 

方法:

public void AddNotice(Notice _notice) 
    { 
     int count = GetAllNotices().Where(x => x.UserID == _notice.UserID).Where(x => x.ProductID == _notice.ProductID).Count(); 
     if (count == 0) 
      notice.InsertNotic(_notice); 
     else 
      notice.UpdateNotic(_notice); 
    } 
    public List<Notice> GetAllNotices() 
    { 
     return notice.GetAllNotices(); 
    } 

和:

public void UpdateNotic(Notice _notic) 
     { 
      db.Entry(_notic).State = EntityState.Modified; 
      db.Configuration.ValidateOnSaveEnabled = false; 
      db.SaveChanges(); 
      db.Configuration.ValidateOnSaveEnabled = true; 
     } 

当运行更新我得到错误db.SaveChanges();

型“System.Data.Entity.Infrastructure.DbUpdateConcurrencyException”的异常出现在EntityFramework.dll但在用户代码中没有处理

附加信息:商店更新,插入或删除语句 影响意外行数(0)。实体可能已被 修改或删除,因为实体被加载

我不知道什么是问题?

+0

您使用实体框架添加和更新的方法是......非常......您没有'DataModel' /'ApplicationDbContext'类吗?你的语句应该像'db.Notices.Add(entity)'或'db.Notices.AddOrUpdate(entity)'来添加或更新 – Ian

回答

0

在您的AddNotice更新案例中,Notice实例不是从您用于更新它的相同上下文中获取的。

更改跟踪取决于与上下文关联的实体,然后进行更新。

或者您可以使用IDbSet<T>.Attach(entity)关联其他地方创建的实例。

相关问题