违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。S级乌龙,自己制造的笑话

项目中碰到一个错误,捯饬了一个半小时没解决,吃完饭继续搞~

 

EF新增多表管理数据时报错:违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。

 

最终问题解决后,完全是因为自己的粗心,出了这样的错误。

 

场景描述:有一个类A,然后有一个类B,多对多关系,新增A的时候,要同时增加B。使用Entity Framework 6处理

代码如下:

public bool AddWithNotice(Announcement entity)
        {
            using (MyDbContext db = new MyDbContext())
            {
                if (entity.OfMsg.Any())
                {
                    db.Msg.AddRange(entity.OfMsg.Select(s => s.Msg).ToList());
                }
                db.Announcements.Add(entity);
                return db.SaveChanges() > 0;
            }
        }

写了很多这样的业务了,都是这样处理的,这个也是这样,完成了Repository的实现,准备测试下数据然后收工,带着激动的心情填写完数据后,提交,然后异常了!

 

 

 

“/”应用程序中的服务器错误。


违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。

说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.Data.ConstraintException: 违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。
源错误:

行 35: //entity.OfMsg = null;

行 36: db.Announcements.Add(entity);

行 37: return db.SaveChanges() > 0;

行 38: }

行 39: return false;

源文件: E:\Github\000\TRUMP\TRUMP.EF\Repository\AnnouncementRepository.cs : 37
堆栈跟踪:

[ConstraintException: 违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。]

System.Data.Entity.Core.Mapping.Update.Internal.KeyManager.GetPrincipalValue(PropagatorResult result) +334

System.Data.Entity.Core.Mapping.Update.Internal.UpdateCompiler.BuildSetClauses(DbExpressionBinding target, PropagatorResult row, PropagatorResult originalRow, TableChangeProcessor processor, Boolean insertMode, Dictionary`2& outputIdentifiers, DbExpression& returning, Boolean& rowMustBeTouched) +262

System.Data.Entity.Core.Mapping.Update.Internal.UpdateCompiler.BuildInsertCommand(PropagatorResult newRow, TableChangeProcessor processor) +105

System.Data.Entity.Core.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler) +342

[UpdateException: 更新条目时出错。有关详细信息,请参阅内部异常。]

System.Data.Entity.Core.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler) +702

System.Data.Entity.Core.Mapping.Update.Internal.<ProduceDynamicCommands>d__a.MoveNext() +850

System.Linq.<ConcatIterator>d__59`1.MoveNext() +190

System.Data.Entity.Core.Mapping.Update.Internal.UpdateCommandOrderer..ctor(IEnumerable`1 commands, UpdateTranslator translator) +314

System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ProduceCommands() +174

System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +83

System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) +9

System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction) +120

System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +77

System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() +11

System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288

System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +163

System.Data.Entity.Core.Objects.<>c__DisplayClass2a.<SaveChangesInternal>b__27() +22

System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +164

System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +224

System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +7

System.Data.Entity.Internal.InternalContext.SaveChanges() +114

[DbUpdateException: 更新条目时出错。有关详细信息,请参阅内部异常。]

System.Data.Entity.Internal.InternalContext.SaveChanges() +199

System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +27

System.Data.Entity.DbContext.SaveChanges() +20

TRUMP.EF.Repository.AnnouncementRepository.AddWithNotice(Announcement entity) in E:\Github\000\TRUMP\TRUMP.EF\Repository\AnnouncementRepository.cs:37

TRUMP.Application.Service.AnnouncementService.AddWithNotice(AnnouncementDto model) in E:\Github\000\TRUMP\TRUMP.Application\Service\AnnouncementService.cs:40

TRUMP.MvcAdmin.Areas.Manager.Controllers.AnnouncementsController.Create(AnnouncementDto model) in E:\Github\000\TRUMP\TRUMP.MvcAdmin\Areas\Manager\Controllers\AnnouncementsController.cs:108

lambda_method(Closure , ControllerBase , Object[] ) +103

System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14

System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27

System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22

System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32

System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50

System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228

System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10

System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34

System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26

System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100

System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27

System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13

System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36

System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12

System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26

System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10

System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21

System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29

System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49

System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28

System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9

System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493

System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48

System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159


版本信息: Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.7.2556.0

 

重试,重启VS,还是继续报错。

 

分析一下应该是哪里关系配置有问题,自己检查了一遍,没发现哪里不对。

去掉第35行注释,保存成功,加上注释报错。明显就是关联表的问题,但是无论是调试跟踪还是其他的方法都在细化异常,只得到“违反了引用完整性约束。Dependent Role 具有多个具有不同值的主体。”这个比较模糊的错误,百度和google均没有结果。

 

此时想打人的欲望11000%。强忍烦躁的心情(不知道为什么这么烦躁),继续调试一直到下班,没解决!

 

实在没有了兴趣继续围着这么莫名其妙的问题了,回家吃饭,饭后依然有些纠结,打开VS,F5还是这错误。WTF,为什么我换了个地方还不好,什么鬼!!!!!

 

下班前就拿着和另一个模块比对了,相同的业务逻辑,那个就好好的。也是怪了,虽然一直怀疑是实体关系配置错误,可是有仔细检查了两三遍配置的代码没发现问题。

这会吃过饭了,某宝某东上转了下,购物车依然在嘲笑银行卡的余额。当年没有直接买两根8G条,现在一百个追悔莫及

 

打开Sql Server数据库,看了下关联表的外键和主键,忽然觉得不对

image

 

what?好像有点问题哦

看了下Fluent Api配置的内容:

HasMany(s => s.OfMsg).WithRequired().HasForeignKey(s => s.MsgScheduleId);

 

你大爷的。把外键指定错了~

搞了个大乌龙,折腾了有三个小时愣是没解决。

 

解决方案:仔细检查关联的类,外键关系配置是否正确 。怪不得百度不到这个问题,估计是犯这个错误的独我一份!

 

再次为自己的重启VS,换电脑重启解决方案以期能解决问题的愚蠢行径感到可笑。我一定是一个假的程序员!

posted @ 2018-01-17 22:49  天北涯  阅读(1486)  评论(1编辑  收藏  举报