Reputation: 307
I have an attached graph object and I can't figure out how to change the foreign key on a record. I have a Load record saved in my db. I retrieve said record by id with tracking on. I
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; }
}
I then retrieve the customer record that I want to associate with the Load record
public partial class Customer
{
[Key]
public virtual int Id {get;set;}
[Required]
[MaxLength(100)]
public virtual string Name { get; set; }
}
No matter what I do, I get some sort of exception is thrown.
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();
What is the proper way to go about changing the foreign key relationship on an attached graph object?
Edit. I have added the exception.
[InvalidOperationException: Attaching an entity of type 'Triton.Core.Models.Identity.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.] 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.InternalSet1.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 Triton.Service.LoadService.UpdateCustomer(Load load, Int32 customerId, Int32 userId) in d:\BitBucket\trunk\Triton\Triton.Service\LoadService.cs:73 Triton.Web.Controllers.LoadsController.Customer(LoadViewModel model) in d:\BitBucket\trunk\Triton\Triton.Web\Controllers\LoadsController.cs:138 lambda_method(Closure , ControllerBase , Object[] ) +180 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +434 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) +60 System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36 System.Web.Mvc.Async.WrappedAsyncResult2.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.<>c__DisplayClass46.b__3f() +323 System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +323 System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +44 System.Web.Mvc.Async.WrappedAsyncResult1.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.<>c__DisplayClass2b.b__1c() +72 System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +184 System.Web.Mvc.Async.WrappedAsyncResult1.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.WrappedAsyncVoid1.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.WrappedAsyncVoid1.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.WrappedAsyncVoid1.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& completedSynchronously) +155
Upvotes: 0
Views: 125
Reputation: 307
It turned out I had an object in a sub class that was being referenced so EF was trying to add it to the graph. Once I nullified that object, everything worked properly.
Upvotes: 0