MVC将包含2个模型的模型中的数据保存到数据库中

时间:2018-01-07 09:16:32

标签: c# asp.net-mvc entity-framework model-view-controller

首先解决:

db.KreatoryZamowien.Add(model.KreatorZamowien);
db.Nabywcy.Add(model.Nabywca);
db.SaveChanges();

即将数据添加到两个表中。如何将相关ID添加到联结表(NabywcaKreatorzamowien)?

******************问题:*************** 我已经创建了相关的表,想出了如何在我的View中显示这些数据。 (jejejej)现在,当我试图将数据保存到数据库时,我得到了例外。

例外:

System.NullReferenceException occurred
  HResult=0x80004003
  Message=The object reference has not been set to the instance of the object.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at Panele.Controllers.KreatorZamowienController.Create(KreatorZamowienNabywca model) in C:\Users\bplos\Source\Repos\Panele\Panele\Controllers\KreatorZamowienController.cs:line 81
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()

异常出现在控制器内:

emp.KreatorZamowien.NumerZamowienia = model.KreatorZamowien.NumerZamowienia;

我不知道为什么,因为它从模型中获取价值并分配给对象。:(

我的数据库架构:

KreatorZamowien(Id, NumerZamowienia)  -------------------------------|
                                                                     |
NabywcaKreatorzamowien (KreatorZamowien_Id, Nabywca_Nabywca_Id)------|
                                                                     |
Nabywca(Nabywca_Id, Nazwa) ------------------------------------------|

我的模特:

KreatorZamowien.cs

public class KreatorZamowien
    {
        public int Id { get; set; }
        public int NumerZamowienia { get; set; }
        public virtual ICollection<Nabywca> Nabywcy { get; set; }
    }

Nabywca.cs

 public class Nabywca
    {
        public int NabywcaId { get; set; }
        public string Nazwa { get; set; }
        public virtual ICollection<KreatorZamowien> KreatoryZamowien { get; set; }
    }

包含2个模型的模型,可在视图中显示它们: KreatoryZamowienNabywca.cs

 public class KreatorZamowienNabywca
    {
        public KreatorZamowien KreatorZamowien { get; set; }
        public Nabywca Nabywca { get; set; }
    }

我的 Create.chtml 查看:

@model Panele.Models.KreatorZamowienNabywca
@using (Ajax.BeginForm("Create", "KreatorZamowien", new AjaxOptions { HttpMethod = "POST", LoadingElementId = "loader", OnSuccess = "onAjaxRequestSuccess" }, new
{
    @id = "AjaxformId",
    @class = "form-horizontal",
    role = "form"
}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

   @Html.DisplayNameFor(m => m.KreatorZamowien.NumerZamowienia)
   @Html.TextBoxFor(m => m.KreatorZamowien.NumerZamowienia)

  @Html.DisplayNameFor(m => m.Nabywca.Nazwa)
  @Html.TextBoxFor(m => m.Nabywca.Nazwa)

  <input id="btnSubmit" class="ico2" type="submit" value="Zapisz zamówienie" form="AjaxformId" />
}

KreatorZamowienController.cs

public class KreatorZamowienController : Controller

    {
        private ShopContext db = new ShopContext();

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Create(KreatorZamowienNabywca model)
        {
            try
            {
                // Verification  
                if (ModelState.IsValid)
                {
                    ShopContext db = new ShopContext();

                    KreatorZamowienNabywca emp = new KreatorZamowienNabywca();
                    emp.KreatorZamowien.NumerZamowienia = model.KreatorZamowien.NumerZamowienia;

                    emp.Nabywca.Nazwa = nabywca.Nazwa;

                    db.KreatoryZamowien.Add(emp.KreatorZamowien);
                    db.Nabywcy.Add(emp.Nabywca);
                    db.SaveChanges();


                    // Info.  
                    return this.Json(new
                    {
                        EnableSuccess = true,
                        SuccessTitle = "Success",
                        SuccessMsg = "Zapisano zamówienie o numerze: " + model.KreatorZamowien.NumerZamowienia + "."
                    });
                }

            }
            catch (Exception ex)
            {
                // Info  
                Console.Write(ex);
                throw ex;
            }
            // Info  
            return this.Json(new
            {
                EnableError = true,
                ErrorTitle = "Error",
                ErrorMsg = "Coś poszło nie tak! Sprawdź formularz."
            });
            //return View(model);
        }

0 个答案:

没有答案