Updating one entity with one context, and inserting a new with another context?

后端 未结 1 1366
暗喜
暗喜 2021-01-24 07:01

Greetings and thanks for reading my post.. :

I am updating an entry (Photo) within a using

using (context = new PhotoEntities())
{
    // ...

    cont         


        
1条回答
  •  醉梦人生
    2021-01-24 07:47

    The answer to this question is just a reminder to myself and to everyone else having issues to understand why Entity Framework inserts, updates etc.. fails with no obvious chance to get a specific error out of it "out of the box".

    So by doing stuff like this :

    try
                {
                    pcontext.SaveChanges();
                }
                catch (System.Data.Entity.Core.UpdateException e)
                {
    
                }
    
                catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
                {
                    Console.WriteLine(ex.InnerException);
                }
    
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException);
                    throw;
                }
    

    you can actually get the exact and very specific error you are looking for.

    In my case.. i forgot to set Auto Increment on the identity, resulting in all records inserted was of ID 0 (zero).

    0 讨论(0)
提交回复
热议问题