使用一个上下文更新一个实体,并使用另一个上下文插入新实体?

问候和感谢阅读我的post..:

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

using (context = new PhotoEntities()) { // ... context.Entry(photo).State = EntityState.Modified; } 

问题是当我使用保存此条目时

 success = context.SaveChanges() > 0; if (success) { FeedServices.CreatePhotoFeed(photo); } 

我仍然需要有上下文,因为我正在插入一个新的feed。 所以..我尝试使用不同的上下文,我遇到一个错误,说:

 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(零)。