c# - 用一个上下文更新一个实体,并在另一个上下文中插入一个新实体?

标签 c# entity-framework

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

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

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

最佳答案

这个问题的答案只是提醒我自己和其他有问题的人来理解为什么 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(零)。

关于c# - 用一个上下文更新一个实体,并在另一个上下文中插入一个新实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878739/

相关文章:

c# - ASP.NET Core 项目 - 发布不显示 "Database Migrations"选项

visual-studio-2010 - Entity Framework 模型中的存储过程

.net - 使用带有自定义连接对象的 EF 存储库?

c# - 创建对象泛型类

c# - 横向扩展WCF,如何处理回调?

c# - Console.Read换行符

entity-framework - 我可以在 Windows 8.1 商店应用程序中使用 Entity Framework 6 吗?

c# - 定义运算符 + 、 = 和 +=

c# - 推荐一个扎实的.Net FTP库

c# - 如何将类实例转换为 JsonDocument?