簡體   English   中英

通過實體框架向SQL Server插入新記錄失敗

[英]failed insert new record to sql server via entity framework

我下面有代碼。 我想通過實體框架5.0將新記錄插入sql-server。 不幸的是,它失敗了。 單擊“保存”按鈕后,記錄不進入數據庫。 任何人都可以幫助我,將不勝感激。


@model IEnumerable<MvcApplication1.Models.ProductListViewModel>

@{
    ViewBag.Title = "ProductList";
}

<h2>ProductList</h2>

<p>
    @Html.ActionLink("Create New", "ProductCreate")
</p>
<table>
    <tr>
        <th align="left">
            ProductName
        </th>
        <th align="left">
            UnitPrice
        </th>
        <th align="left">
            Supplier
        </th>
        <th align="left">
            Categorie
        </th>
        <th align="left">
            Discontinued
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ProductName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UnitPrice)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Supplier)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Categorie)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Discontinued)
            </td>
            <td>
                @Html.ActionLink("Edit", "ProductEdit", new { ProductId = item.ProductId }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
    }

</table>

@model MvcApplication1.Models.ProductEditViewModel

@{
    Layout = null;
}

<script type="text/javascript">

</script>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ProductEdit</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Product</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.Product.ProductID)

            <div class="form-group">
                @Html.LabelFor(model => model.Product.ProductName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Product.ProductName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Product.ProductName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Product.SupplierID, "SupplierID", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @*DropDownList is for deiplay purpose*@
                    @*@Html.DropDownList("SupplierID", Model.SupplierItems, htmlAttributes: new { @class = "form-control" })*@

                    @*DropDownListFor is for Edit purpose*@
                    @Html.DropDownListFor(model => model.Product.SupplierID, Model.SupplierItems, htmlAttributes: new { @class = "form-control" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Product.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @*RadioButton is for Display purpose*@
                    @*@foreach (var Categorie in Model.CategorieItems)
                        {
                            @Html.RadioButton("CategoryID", Categorie.CategoryID, Model.CategorySelectedId == Categorie.CategoryID) @Categorie.CategoryName; @:&nbsp;&nbsp;&nbsp;
                        }*@

                    @*RadioButtonFor is for Edit purpose*@
                    @foreach (var Categorie in Model.CategorieItems)
                    {
                        @Html.RadioButtonFor(model => model.Product.CategoryID, Categorie.CategoryID) @Categorie.CategoryName; @:&nbsp;&nbsp;&nbsp;
                    }

                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Product.UnitPrice, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Product.UnitPrice, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Product.UnitPrice, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Product.Discontinued, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.Product.Discontinued)
                        @Html.ValidationMessageFor(model => model.Product.Discontinued, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Mvc;

namespace MvcApplication1.Models
{
    public class NorthwindRepository
    {
        public NorthwindEntities northwind;

        public NorthwindRepository()
        {
            // sample for populate sql server database table via entity framework
            // 1. Install EntityFramework 5.0, if previous sample for using populate oracle database table via entity framework has been installed, this can be skiped : execute command at Package Manager Console "Install-Package EntityFramework -Version 5.0.0" ( Oracle data access provider ODAC 12.1.0.1.2 current is not support (work with) EntityFramework version 6 ). If you want uninstall EntityFramework 5, using command "unInstall-Package EntityFramework -Version 5.0.0"
            // 2. Models => Add => New item => Data => Ado.Net Entity Data Model ( using EntityFramework 5.0 )
            // northwind = new NorthwindEntities();  // 3. this is connectionStrings name="NorthwindEntities"

            northwind = new NorthwindEntities();
        }

        public Product GetProductById(Int32? ProductId)
        {
            return (ProductId == null ? new Product() :
             (from pro in northwind.Products
              where pro.ProductID == ProductId
              select pro).FirstOrDefault());
        }

        // For DropDownListFor need IEnumerable<SelectListItem>
        public IEnumerable<SelectListItem> SupplierItems(Int32? SelectedSupplierID)
        {
            SelectListItem[] q0 = { new SelectListItem { Text = "", Value = null, Selected = false } };

            var q1 = from sup in northwind.Suppliers.AsEnumerable()
                     select new SelectListItem
                     {
                         Text = sup.CompanyName,
                         Value = sup.SupplierID.ToString(),
                         Selected = sup.SupplierID == SelectedSupplierID
                     };


            var q3 = q0.Union(q1);

            return q3;
        }

        // For RadioButtonFor need below
        public IEnumerable<Category> CategorieItems
        {
            get
            {
                var q = from cat in northwind.Categories.AsEnumerable() select cat;
                return q;
            }
        }

        public IEnumerable<ProductListViewModel> GetProductList
        {
            get
            {
                var q = from pro in northwind.Products
                        select new ProductListViewModel
                        {
                            ProductId = pro.ProductID,
                            ProductName = pro.ProductName,
                            Supplier = pro.Supplier.CompanyName,
                            Categorie = pro.Category.CategoryName,
                            Discontinued = pro.Discontinued,
                            UnitPrice = pro.UnitPrice
                        };
                return q.AsEnumerable();
            }
        }

        public void Save()
        {
            this.northwind.SaveChanges();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Web.Script.Serialization;
using MvcApplication1.Models;
using System.Data.Objects.SqlClient;
using System.Data;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        // sample for populate sql server database table via entity framework
        public ActionResult ProductList()
        {
            ProductListViewModel vm = new ProductListViewModel();
            return View(vm.repository.GetProductList);
        }

        [HttpGet]
        public ActionResult ProductEdit(Int32 ProductId)
        {
            return View(PopulateProductEditViewModel(ProductId));
        }

        [HttpPost]
        public ActionResult ProductEdit(Int32 ProductId, FormCollection fc)
        {
            var vm = PopulateProductEditViewModel(ProductId);
            UpdateModel(vm.Product, "Product");
            vm.repository.Save();
            return RedirectToAction("ProductList");
        }

        private ProductEditViewModel PopulateProductEditViewModel(Int32? ProductId)
        {
            var vm = new ProductEditViewModel();
            vm.Product = vm.repository.GetProductById(ProductId);
            return vm;
        }

        [HttpGet]
        public ActionResult ProductCreate()
        {
            return View("ProductEdit", PopulateProductEditViewModel(null));
        }

        [HttpPost]
        public ActionResult ProductCreate(FormCollection fc)
        {
            var vm = PopulateProductEditViewModel(null);
            UpdateModel(vm.Product, "Product");
            vm.repository.Save();
            return RedirectToAction("ProductList");
        }
    }
}

正確的代碼如下。


vm.repository.northwind.Products.Add(vm.Product);

[HttpPost]
public ActionResult ProductCreate(FormCollection fc)
{
    var vm = PopulateProductEditViewModel(null);
    UpdateModel(vm.Product, "Product");
    vm.repository.northwind.Products.Add(vm.Product);
    vm.repository.Save();
    return RedirectToAction("ProductList");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM