bilal-fazlani / tracker-enabled-dbcontext

Tracker-enabled DbContext offers you to implement full auditing in your database
https://tracker-enabled-dbcontext.bilal-fazlani.com/
Other
217 stars 110 forks source link

System.Collections.Generic.KeyNotFoundException #160

Closed hello-code closed 6 years ago

hello-code commented 6 years ago

When savechanges will show System.Collections.Generic.KeyNotFoundException

System.Collections.Generic.Dictionary`2.get_Item(TKey key) +11759657
   EntityFramework.MappingAPI.Mappers.MapperBase.BindForeignKeys() in c:\dev\EntityFramework.MappingAPI\trunk\src\EntityFramework.MappingAPI\Mappers\MapperBase.cs:618
   EntityFramework.MappingAPI.Mappings.DbMapping..ctor(DbContext context) in c:\dev\EntityFramework.MappingAPI\trunk\src\EntityFramework.MappingAPI\Mappings\DbMapping.cs:103
   EntityFramework.MappingAPI.EfMap.Get(DbContext context) in c:\dev\EntityFramework.MappingAPI\trunk\src\EntityFramework.MappingAPI\EfMap.cs:60
   EntityFramework.MappingAPI.Extensions.MappingApiExtensions.Db(DbContext ctx, Type type) in c:\dev\EntityFramework.MappingAPI\trunk\src\EntityFramework.MappingAPI\Extensions\MappingApiExtensions.cs:51
   TrackerEnabledDbContext.Common.Configuration.DbMapping..ctor(ITrackerContext context, Type entityType) +39
   TrackerEnabledDbContext.Common.Auditors.LogAuditor.CreateLogRecord(Object userName, EventType eventType, ITrackerContext context, ExpandoObject metadata) +125
   TrackerEnabledDbContext.Common.CoreTracker.AuditChanges(Object userName, ExpandoObject metadata) +246
   CallSite.Target(Closure , CallSite , CoreTracker , Object , Object ) +158
   System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3(CallSite site, T0 arg0, T1 arg1, T2 arg2) +699
   TrackerEnabledDbContext.TrackerContext.SaveChanges(Object userName) +468
   TrackerEnabledDbContext.TrackerContext.SaveChanges() +77
   XL.Controllers.ExceptionController.DeleteExceptionType(Int32 id) in E:\Project\App\XL\XL\Controllers\ExceptionController.cs:112
   lambda_method(Closure , ControllerBase , Object[] ) +97
   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() +225
   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() +9739301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Model:

    [TrackChanges]
    [Table("ExceptionType")]
    public class ExceptionType
    {
        public int Id { get; set; }

        [Required, StringLength(10, MinimumLength = 1)]
        [Index("UQ_Description", 1, IsUnique = true)]
        public string Description { get; set; }

        public virtual ICollection<ExceptionItem> ExceptionItems { get; set; }
    }

    [TrackChanges]
    [Table("ExceptionItem")]
    public class ExceptionItem
    {
        public int Id { get; set; }
        public string Description { get; set; }

        [ForeignKey("ExceptionType")]
        public int ExceptionTypeId { get; set; }
        public virtual ExceptionType ExceptionType { get; set; }
    }

context:

  public class AppContext : TrackerContext
    {
        public AppContext() : base("name=DefaultConnection") { }

        public DbSet<ExceptionType> ExceptionType { get; set; }
        public DbSet<ExceptionItem> ExceptionItem { get; set; }
    }

Controller:

 public ActionResult CreateExceptionType([Bind(Include = "Id,Description")] ExceptionType exceptionType)
        //public ActionResult CreateExceptionType(ExceptionType exceptionType)
        {
            if (ModelState.IsValid)
            {
                db.ExceptionType.Add(exceptionType);
                try
                {
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError(string.Empty, "sth is wrong!");
                    return View(exceptionType);
                }
            }

            return View(exceptionType);
        }

      public ActionResult EditExceptionType([Bind(Include = "Id,Description")] ExceptionType exceptionType)
        {
            if (ModelState.IsValid)
            {
                db.Entry(exceptionType).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError(string.Empty, "sth is wrong!");
                    return View(exceptionType);
                }
            }
            return View(exceptionType);
        }

        [HttpPost, ActionName("DeleteExceptionType")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteExceptionType(int id)
        {
            ExceptionType exceptionType = db.ExceptionType.Find(id);
            db.ExceptionType.Remove(exceptionType);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Global.asax.cs:

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalTrackingConfig.DisconnectedContext = true;
        }
hello-code commented 6 years ago

I found this is not tracker-enabled-dbcontext's issue. The System.Collections.Generic.KeyNotFoundException is about multiple foreign key.

this solved.