Ashkan Hafezi
Ashkan Hafezi

Reputation: 49

entity framework doesnt allow to save data in db

i am using entityframework codefirst in my application.
i have 2 tables:
1.Order
2.Orderdetails
i want to collect data from a form and save it in these 2 tables in one action. my form uses a viewmodel called "OrderViewModel".
i want to save data in "Order" table and "Orderdetail" table when user clicks submit. but i have blow error:

The model item passed into the dictionary is of type

'Amooshahryar.Models.Order', but this dictionary requires a model item of type 'Amooshahryar.Models.ViewModels.OrderViewModel'.

my form uses 'Amooshahryar.Models.ViewModels.OrderViewModel' and in actionresult i want to save data in Order table witch uses 'Amooshahryar.Models.Order'.
i cant understand what cuases problem.
here is my code:

 public ActionResult آدرس_و_پرداخت(FormCollection values)
    {


        var order = new Order() {};

        TryUpdateModel(order);

        int totalcartprice = 0;

        try
        {
            order.Username = User.Identity.Name;
            order.OrderDate = DateTime.Now;
            order.DeliveryStatusID = 1;

            TryUpdateModel(order);

                //Save Order
                db.Orders.Add(order);
                db.SaveChanges(); <===========here i get error

                //Process the order


            //And rest of the code that i havent write here
        }
        catch
        {
            //Invalid - redisplay with errors
            return View(order);
        }
    }

any help is appritiated ...
thank you.

Edit:
This is my stack trace:

[InvalidOperationException: The model item passed into the dictionary is of type 'Amooshahryar.Models.Order', but this dictionary requires a model item of type 'Amooshahryar.Models.ViewModels.OrderViewModel'.] System.Web.Mvc.ViewDataDictionary1.SetModel(Object value) +378 System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47 System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +614 System.Web.Mvc.ViewDataDictionary1..ctor(ViewDataDictionary viewDataDictionary) +37 System.Web.Mvc.WebViewPage1.SetViewData(ViewDataDictionary viewData) +98 System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +425 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.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) +106 System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +321 System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +185 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() +133 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37 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() +133 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37 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() +133 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37 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() +9748493 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

Upvotes: 0

Views: 49

Answers (1)

ADyson
ADyson

Reputation: 62059

This is what is happening:

1) Your db.SaveChanges fails for some reason, and an exception is thrown.

2) The code moves to the Catch block because of this.

3) You ignore the exception, and try to execute a return statement. Unfortunately your return statement also fails because you passed the wrong type of object. This then produces the exception you see on your screen, because that's not caught.

Don't squash exceptions like this. If an exception happens it's because something unusual happened and something is actually wrong, and so it's fine for the application to crash. Don't hide it, and please always log it and investigate it. Try-catch is for catching only unavoidable exceptions. A database crash should not be unavoidable, it should be unusual. Also if your return statement within the catch did succeed, the user gets no feedback that there's a problem and is left wondering why they're on the same screen again. Meanwhile you as the developer get no notice that your app is broken

Upvotes: 1

Related Questions