2015-11-26 36 views
0

嗨,所以每次调用savechanges()时都要遇到这个异常。还有一个帖子有多个答案,但我不能指出哪个答案适合我的问题。而且似乎每个人对这个例外都有不同的看法。DbUpdateException未处理?

链接到其他岗位:[链接] Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

我的例外:

的类型 'System.Data.Entity.Infrastructure.DbUpdateException' 未处理的异常出现在 EntityFramework.dll

附加信息:更新条目时发生错误。 有关详细信息,请参阅内部例外。

我试图将邮件保存到我的存储中。我使用实体框架6.1.3和SQL服务器2014年

这是我的方法存储邮件:

public int StoreMail(PhishingMail PhishingMail) 
{ 
    using (var phishingMailStorage = new PhishFinderDBModel()) 
    { 
     try 
     { 
      //// var manager = ((IObjectContextAdapter)phishingMailStorage).ObjectContext.ObjectStateManager; 
      //// phishingMailStorage.PhishingMail.Attach(PhishingMail); 
      phishingMailStorage.Entry(PhishingMail).State = PhishingMail.PhishingMailId == 0 ? EntityState.Added : EntityState.Modified; 
      phishingMailStorage.SaveChanges(); 

      //// manager.ChangeObjectState(PhishingMail, EntityState.Modified); 
      //// phishingMailStorage.SaveChanges(); 

      Console.WriteLine("Het is gelukt"); 
     } 
     catch (OptimisticConcurrencyException) 
     { 
      var ctx = ((IObjectContextAdapter)phishingMailStorage).ObjectContext; 

      ctx.Refresh(RefreshMode.ClientWins, phishingMailStorage.PhishingMail); 
      phishingMailStorage.SaveChanges(); 
     } 
    } 

    return PhishingMail.PhishingMailId; 
} 

这是我的GET方法的邮件,也没有工作:

public List<PhishingMail> GetEmails() 
{ 
    phishingMailList = new List<PhishingMail>(); 
    FolderId InboxId = new FolderId(WellKnownFolderName.Inbox, "******@******.nl"); 
    FindItemsResults<Item> findResults = service.FindItems(InboxId, new ItemView(20)); 

    foreach (Item phishingmail in findResults.Items) 
    { 
     if (!((EmailMessage)phishingmail).IsRead) 
     { 
      /// ((EmailMessage)phishingmail).IsRead = true; 
      ((EmailMessage)phishingmail).Update(ConflictResolutionMode.AutoResolve); 
     } 

     PhishingMail mail = MailMapper.Map((EmailMessage)phishingmail); 

     //// ((EmailMessage)phishingmail).Load(new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead)); 
     phishingMailList.Add(mail); 

     /// Console.WriteLine(mail.Type); 
    } 

    return phishingMailList; 
} 

为什么savechanges()不起作用,我如何使它工作?

谢谢。

+0

哪一行产生异常,什么是内部异常? –

+0

看起来像您可能想要捕获'DbUpdateException'并查看异常详细信息以找出发生了什么问题。 – user1666620

回答

0

编写你的db.SaveChanges();方法在try块内。它会告诉你确切的问题

try 
{ 
    db.SaveChanges(); 
} 
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) 
{ 
    Exception raise = dbEx; 
    foreach (var validationErrors in dbEx.EntityValidationErrors) 
    { 
     foreach (var validationError in validationErrors.ValidationErrors) 
     { 
       string message = string.Format("{0}:{1}", 
       validationErrors.Entry.Entity.ToString(), 
       validationError.ErrorMessage); 

       raise = new InvalidOperationException(message, raise); 
     } 
     } 
     throw raise; 
}