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.EntityReference1.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.InternalSet1.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.DbEntityEntry1.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, IDictionary2 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.WrappedAsyncResultBase1.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.WrappedAsyncResultBase1.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.WrappedAsyncResultBase1.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.WrappedAsyncResultBase1.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.WrappedAsyncResultBase1.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.WrappedAsyncResultBase1.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
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.
Related
This is the screenshot of the reoccurring error
whenever I connect my customerController to the database it shows this error. I am new to .net and was building this project. Could you please explain how to resolve this issue and what is the actual cause of it.
[![Stack Trace of Error](https://i.stack.imgur.com/ITLui.png)](https://i.stack.imgur.com/ITLui.png)
This is the CustomerController Class
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Vidly.Models;
using System.Data.Entity;
using IdentitySample.Models;
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ViewResult Index()
{
var customers = _context.Customers.ToList();
return View(customers);
}
}
}
This is the Customer class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public bool isSubscribeToNewsLetter { get; set; }
public MembershipTypes MembershipType { get; set; }
public byte MembershipTypeId { get; set; }
}
}
Whenever I pass the reference of the customer class to the customer controller so that it can access the details of the customers stored there, then the error occurs.
But if I hardcode the same thing then it works perfectly. Currently my customer table has 2 customers, which I created using the code-first approach.
Edit:
The Full Stack Trace:
[SqlException (0x80131904): Cannot drop database "aspnet-MvcMovie" because it is currently in use.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2585494 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +6038654
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +297
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4477
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +997
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +314 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +297 System.Data.Entity.Infrastructure.Interception.<>c.<NonQuery>b__4_0(DbCommand t, DbCommandInterceptionContext1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +427
System.Data.Entity.SqlServer.<>c__DisplayClass57_0.b__0(DbConnection conn) +111
System.Data.Entity.SqlServer.<>c__DisplayClass60_0.b__0() +443
System.Data.Entity.SqlServer.<>c__DisplayClass2_0.b__0() +10
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +189 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78 System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) +175
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +552 System.Data.Entity.SqlServer.SqlProviderServices.DropDatabase(SqlConnection sqlConnection, Nullable1 commandTimeout, String databaseName) +317
System.Data.Entity.SqlServer.SqlProviderServices.DbDeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +243 System.Data.Entity.Core.Common.DbProviderServices.DeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +76
System.Data.Entity.Core.Objects.ObjectContext.DeleteDatabase() +134
System.Data.Entity.Internal.DatabaseOperations.Delete(ObjectContext objectContext) +12
System.Data.Entity.Database.Delete() +222
System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context) +144 System.Data.Entity.Internal.<>c__DisplayClass66_01.b__0() +76
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +372
System.Data.Entity.Internal.<>c.b__58_0(InternalContext c) +9
System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +129 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +196
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +86
System.Data.Entity.Internal.InternalContext.Initialize() +30
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53 System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() +15
System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +53 System.Collections.Generic.List1..ctor(IEnumerable1 collection) +174 System.Linq.Enumerable.ToList(IEnumerable1 source) +61 Vidly.Controllers.CustomersController.Index() in D:\C# and .Net\Practice\Vidly\Vidly\Controllers\CustomerController.cs:25 lambda_method(Closure , ControllerBase , Object[] ) +61
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor,IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.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.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.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() +9850389
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
I have a table DivorceCases which has many fields and it's model is like:
[Key]
[Required]
public string case_id { get; set; }
public string user_id { get; set; }
public DateTime case_date { get; set; }
public virtual Transactions t { get; set; }
I am trying to add transaction details to an existing row but I am getting a [NullReferenceException: Object reference not set to an instance of an object.] error. In the DivorceCases table EF6 has created a column t_id for foreign key reference of Transactions Table.
I used :
public static void UpdatePayment(string cid,string txnno)
{
DivorceCasesContext db = new DivorceCasesContext();
DivorceCases dc = db.DivorceCase.Where(x => x.case_id == cid).Include(x => x.t).SingleOrDefault();
if (dc.t == null || dc.t.txn_id1 == null || dc.t.txn_id1 == "")
{
dc.t.txn_id1 = txnno;
dc.t.amount1 = amount.ToString();
dc.t.date1 = DateTime.Now.ToString();
}
else
{
dc.t.txn_id2 = txnno;
dc.t.amount2 = amount.ToString();
dc.t.date2 = DateTime.Now.ToString();
}
db.Set<DivorceCases>().Attach(dc);
db.Entry(dc).State = EntityState.Modified;
db.SaveChanges();
}
}
The Error I'm getting is:
[NullReferenceException: Object reference not set to an instance of an object.]
gonylaw.Helpers.Amounts.UpdatePayment(String cid, String txnno) +425
gonylaw.Controllers.PaymentController.PaymentProcessor(CreditCard c) +461
lambda_method(Closure , ControllerBase , Object[] ) +104
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() +9644037
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
You are accessing properties of dc.t without ensuring dc.t is not null. If the if statement short circuits on the first condition, dc.t is null, yet you attempt to assign a value to dc.t.txn_id:
if( dc.t == null || ... )
{
dc.t.txn_id1 = txnno; // null ref exception here
}
Asside from that, there are other improvements I suggest:
public static void UpdatePayment(string cid,string txnno)
{
// add using block to dispose of DbContext after you're done with it
using( DivorceCasesContext db = new DivorceCasesContext() )
{
DivorceCases dc = db.DivorceCase.Include(x => x.t)
.Where( x => x.case_id == cid )
.SingleOrDefault();
// take care of your null ref problem
if( dc.t == null )
{
dc.t = new Transactions();
}
// simplify null/empty string check
if( string.IsNullOrEmpty( dc.t.txn_id1 ) )
{
dc.t.txn_id1 = txnno;
dc.t.amount1 = amount.ToString();
dc.t.date1 = DateTime.Now.ToString();
}
else
{
dc.t.txn_id2 = txnno;
dc.t.amount2 = amount.ToString();
dc.t.date2 = DateTime.Now.ToString();
}
// this is not needed - dc is already attached to the context
// (unless you're doing something nonstandard by default
// within your DbContext)
//db.Set<DivorceCases>().Attach(dc);
//db.Entry(dc).State = EntityState.Modified;
db.SaveChanges();
}
}
}
I made a web with authentication. When I press the logout button the following error shows, but the logout is correct. I mean, if you reload the page the login form appears and works fine.
Server Error in '/' Application.
Value cannot be null or empty.
Parameter name: contentPath
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Value cannot be null or empty.
Parameter name: contentPath
Source Error:
[No relevant source lines]
Source File: c:\Users\User\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs Line: 0
Stack Trace:
[ArgumentException: Value cannot be null or empty.
Parameter name: contentPath]
System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext) +130
System.Web.Mvc.UrlHelper.Content(String contentPath) +42
ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\Users\Manuel\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs:0
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +177
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +80
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +113
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +26
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +210
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +27
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +31
System.Web.WebPages.WebPageBase.Write(HelperResult result) +32
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +101
System.Web.WebPages.WebPageBase.PopContext() +146
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +120
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +297
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +58
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +349
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +69
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +188
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9742689
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is the code to make the logout.
[HttpPost]
public ActionResult Logout()
{
System.Web.Security.FormsAuthentication.SignOut();
Session.Clear();
Session.RemoveAll();
return RedirectToAction("Login", "Login");
}
I tried to make the logout without the session lines but it keeps the session.
This question already has answers here:
The object cannot be deleted because it was not found in the ObjectStateManager
(10 answers)
Closed 8 years ago.
I am getting the following error when I try to delete an object from the datase using LINQ.
The object cannot be deleted because it was not found in the ObjectStateManager.
Note: When I try to run the query directly from the database, the object is deleted.
Code where I am getting the error:
public void deleteStorage(CommonLayer.TblNewsStorage storageToDelete)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
e.TblNewsStorage.DeleteObject(storageToDelete);
e.SaveChanges();
}
}
Stack Trace:
[InvalidOperationException: The object cannot be deleted because it was not found in the ObjectStateManager.]
System.Data.Objects.ObjectContext.DeleteObject(Object entity, EntitySet expectedEntitySet) +3061568
System.Data.Objects.ObjectSet`1.DeleteObject(TEntity entity) +18
DataLayer.DAStorage.deleteStorage(TblNewsStorage storageToDelete) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\DataLayer\DAStorage.cs:38
BusinessLayer.Storage.deleteStorage(String id) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\BusinessLayer\Storage.cs:43
NewsLibrary.Controllers.StorageController.Delete(TblNewsStorage storage) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\NewsLibrary\Controllers\StorageController.cs:61
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9688704
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Try sending the ID of the object you want to delete then query it inside your context instead of sending the whole object :
public void deleteStorage(int ID)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
//Like That
var selectedItem = e.TblNewsStorage.Where( t => t.ID == ID).FirstOrDefault();
e.TblNewsStorage.DeleteObject(selectedItem);
e.SaveChanges();
}
}
try below code:-
e.TblNewsStorage(storageToDelete).State = System.Data.EntityState.Deleted;
e.SaveChanges();
OR
e.TblNewsStorage.Attach(storageToDelete);
e.TblNewsStorage.Remove(storageToDelete);
e.SaveChanges();
Our mvc project with json.net running without any problem on every developer except the one with the new windows 8.1 system. How can we find source of the method not found problem ?
details of the exception ;
[MissingMethodException: Method not found: 'System.Object Newtonsoft.Json.Linq.JToken.ToObject(System.Type)'.]
ExtensionMethods.Eval(Object o, String propertyName) in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\ClassLibrary\ExtensionMethods.cs:136
ASP.<>c__DisplayClass20.<Execute>b__1(CallbackPanelSettings settings) in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\LogiSysMvc\Views\Genel_Personel\GridViewEditFormPartial.cshtml:430
DevExpress.Web.Mvc.UI.ExtensionsFactory.CreateExtension(Action`1 method) +137
DevExpress.Web.Mvc.UI.ExtensionsFactory.CallbackPanel(Action`1 method) +43
ASP._Page_Views_Genel_Personel_GridViewEditFormPartial_cshtml.Execute() in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\LogiSysMvc\Views\Genel_Personel\GridViewEditFormPartial.cshtml:11
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +191
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +762
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +74
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +388
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +303
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +155
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +66
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
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) +68
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
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) +65
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
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) +66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +69
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +123
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +133
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1097
You should check Newtonsoft.Json library version on that computer (also in GAC). Non-generic ToObject methods where introduced in November last year, so there is slight chance this causes problem.