无法更新附加图表上的外键

时间:2015-06-29 16:26:33

标签: c# asp.net-mvc entity-framework-6

我有一个附加的图形对象,我无法弄清楚如何更改记录上的外键。我的数据库中保存了一个加载记录。我通过id检索所述记录并跟踪。我

public partial class Load 
{
    [Key]
    public virtual int Id {get;set;}

    [Required]
    public virtual int AccountId { get; set; }

    public virtual Account Account { get; set; }

    [Required]
    public virtual int CustomerId { get; set; }

    [ForeignKey("CustomerId")]
    public virtual Customer Customer { get; set; }
}

然后我检索了我想要与加载记录关联的客户记录

public partial class Customer
{
    [Key]
    public virtual int Id {get;set;}

    [Required]
    [MaxLength(100)]
    public virtual string Name { get; set; }
}

无论我做什么,我都会遇到某种异常。

        var customer = context.Customers.Where(x => x.Id == customerId).SingleOrDefault();
        load.Customer = customer;
        load.CustomerId = customer.Id;
        load.ModifiedByApplicationUserId = userId;
        load.ModifiedDateTime = DateTime.Now;
        context.Entry(load).State = EntityState.Modified;
        context.SaveChanges();

在附加的图形对象上更改外键关系的正确方法是什么?

编辑。我添加了例外。

  

[InvalidOperationException:附加类型为&#39; Triton.Core.Models.Identity.ApplicationUser&#39;的实体。失败,因为同一类型的另一个实体已具有相同的主键值。使用&#39;附加&#39;方法或将实体的状态设置为“未更改”#39;或者&#39;修改&#39;如果图中的任何实体具有冲突的键值。这可能是因为某些实体是新的并且尚未收到数据库生成的键值。在这种情况下,请使用&#39;添加&#39;方法或“添加”#39;实体状态跟踪图形,然后将非新实体的状态设置为“未更改”。或者&#39;修改&#39;作为适当的。]      System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity,EntitySet entitySet)+690      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity,Boolean doAttach)+130      System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity,Boolean doAttach)+65      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity,Boolean relationshipAlreadyExists,Boolean addRelationshipAsUnchanged,Boolean doAttach)+67      System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity,Boolean addRelationshipAsUnchanged,Boolean doAttach)+340      System.Data.Entity.Core.Objects.DataClasses.EntityReference 1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +209 System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +164 System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity) +510 System.Data.Entity.Internal.Linq.<>c__DisplayClassa.<Attach>b__9() +97 System.Data.Entity.Internal.Linq.InternalSet 1.ActOnSet(Action action,EntityState newState,Object entity,String methodName)+354      System.Data.Entity.Internal.Linq.InternalSet 1.Attach(Object entity) +200 System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value) +357 System.Data.Entity.Infrastructure.DbEntityEntry 1.set_State(EntityState value)+42      drit中的Triton.Service.LoadService.UpdateCustomer(Load load,Int32 customerId,Int32 userId):BitBucket \ trunk \ Triton \ Triton.Service \ LoadService.cs:73      Triton.Web.Controllers.LoadsController.Customer(LoadViewModel模型)在d:\ BitBucket \ trunk \ Triton \ Triton.Web \ Controllers \ LoadsController.cs:138      lambda_method(Closure,ControllerBase,Object [])+180      System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object []参数)+59      System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary 2 parameters) +434 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2个参数)+60      System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod()+76      System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult,ActionInvocation innerInvokeState)+36      System.Web.Mvc.Async.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) +73 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+136      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+102      System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)+49      Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod_callback(IAsyncResult asyncResult)+42      Castle.Proxies.Invocations.AsyncControllerActionInvoker_EndInvokeActionMethod.InvokeMethodOnTarget()+103      Castle.DynamicProxy.AbstractInvocation.Proceed()+ 117      Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed()+48      Glimpse.Mvc.AlternateType.EndInvokeActionMethod.NewImplementation(IAlternateMethodContext context)+152      Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation)+183      Castle.DynamicProxy.AbstractInvocation.Proceed()+483      Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod(IAsyncResult asyncResult)+203      System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d()+117      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass46.b__3f()+323      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass46.b__3f()+323      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass33.b__32(IAsyncResult asyncResult)+44      System.Web.Mvc.Async.WrappedAsyncResult 1.CallEndDelegate(IAsyncResult asyncResult) +47 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+136      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+102      System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)+50      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass2b.b__1c()+72      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass21.b__1e(IAsyncResult asyncResult)+184      System.Web.Mvc.Async.WrappedAsyncResult 1.CallEndDelegate(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+133      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+56      System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)+40      System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult,ExecuteCoreState innerState)+34      System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+139      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+59      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+40      System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+44      System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult,Controller controller)+39      System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +62 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+139      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+59      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+40      System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)+39      System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)+39      System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult,ProcessRequestState innerState)+39      System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase 1.End()+139      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+59      System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,Object tag)+40      System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)+40      System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)+38      System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+9651688      System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

1 个答案:

答案 0 :(得分:0)

事实证明我在一个被引用的子类中有一个对象,所以EF试图将它添加到图形中。一旦我使该对象无效,一切都正常。