【问题标题】:Updating one entity with one context, and inserting a new with another context?用一个上下文更新一个实体,并用另一个上下文插入一个新实体?
【发布时间】:2014-09-19 05:52:32
【问题描述】:

问候并感谢您阅读我的帖子..:

我正在使用中更新条目(照片)

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

    context.Entry(photo).State = EntityState.Modified;
}

问题是当我使用

保存此条目时
success = context.SaveChanges() > 0;
if (success)
{
     FeedServices.CreatePhotoFeed(photo);
}

我仍然需要了解上下文,因为我要插入一个新的提要。所以..我尝试使用不同的上下文,但我遇到了一个错误,上面写着:

An error occurred while updating the entries. 
See the inner exception for details.",
"ExceptionType":"System.Data.Entity.Infrastructure.DbUpdateException",
"StackTrace":"   at System.Data.Entity.Internal.InternalContext.SaveChanges()\r\n  
 at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()\r\n   
at System.Data.Entity.DbContext.SaveChanges()\r\n   
at ServiceLibrary.Services.FeedServices.CreatePhotoFeed(Photo photo) 
in c:\\PhotoApp\\ServiceLibrary

下面是失败的代码:

public static void CreatePhotoFeed(Photo photo)
{
    using (var pcontext = new PhotoEntities())
    {
        // TODO : Guest access handling.,...
        var sourceUser = UserServices.GetLoggedInUser();

        Feed feed = new Feed();
        feed.UserId = sourceUser.Id;
        feed.PhotoId = photo.Id;
        feed.SourceUsername = sourceUser.Firstname + " " + sourceUser.Lastname;
        feed.TargetUsername = photo.User.Firstname + " " + photo.User.Lastname;
        feed.DateCreated = DateTime.UtcNow;
        feed.Feedtext = "lastet opp et nytt foto";
        feed.FeedType = FeedTypeEnum.FeedType.NewPhoto.ToString();

        pcontext.Feeds.Add(feed);

        // this throws the error
        pcontext.SaveChanges();
    }
}

【问题讨论】:

  • 内部异常是什么?对我来说,代码看起来很好。
  • 嗯......你这么说......我发现我可以围绕 saveChanges 上下文运行一个 try catch 块,并且我发现它可以通过 System.Data.Entity 运行。 Infrastructure.DbUpdateException ex 我注意到问题出在表以及 ID 字段是如何构建的:)
  • 非常感谢...这实际上为我节省了很多时间 :) 我如何接受这个问题的答案?
  • IDENTITY(1,1) 是......在插入时非常重要......太糟糕了,如果不运行一些复杂的东西(至少对我来说......),你不会得到一个逻辑错误。抓...

标签: c# entity-framework


【解决方案1】:

这个问题的答案只是提醒我自己和其他所有有问题的人都无法理解为什么 Entity Framework 插入、更新等。失败,没有明显的机会从“开箱即用”中得到特定错误.

所以通过做这样的事情:

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;
            }

您实际上可以获得您正在寻找的确切且非常具体的错误。

在我的情况下..我忘记在标识上设置自动增量,导致插入的所有记录的 ID 为 0(零)。

【讨论】:

  • 这捕获了正确的异常...谢谢!我在桌子上遇到了权限问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多