EF4.4增删改查实例

第一、先创建一个名为Store数据库,将下面脚本代码执行创建表;

USE [Store]
GO

/****** Object:  Table [dbo].[Category]    Script Date: 03/25/2014 09:39:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Category](
    [CategoryID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
 CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

/****** Object:  Table [dbo].[Product]    Script Date: 03/25/2014 09:39:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Product](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [CategoryID] [int] NULL,
    [UnitPrice] [decimal](18, 2) NULL,
    [UnitsInStock] [int] NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

第二、控制器ProductController
//
        // GET: /Product/

        public ActionResult Index()
        {
            var products = db.Products;
            return View(products.ToList());
        }

        /// <summary>
        // GET: /Products/Details/5
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int id = 0)
        {
            var product = db.Products.First(p => p.ID == id);
            if (product == null)
                return HttpNotFound();
            return View(product);
        }

        //
        // GET: /Products/Create
        public ActionResult Create()
        {
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "Name");
            return View();
        }

        //
        // POST: /Products/Create

        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                db.AddToProducts(product);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "Name", product.CategoryID);
            return View(product);
        }

        //
        //GET: /Products/Edit/5
        public ActionResult Edit(int id = 0)
        {
            Product entity = db.Products.First(p => p.ID == id);
            if (entity == null)
                return HttpNotFound();
            ViewBag.CategoryID = new SelectList(db.Categories.ToList(), "CategoryID", "Name", entity.CategoryID);
            return View(entity);
        }

        //
        //POST: /Products/Edit/5
        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                db.CreateObjectSet<Product>().Attach(product);
                db.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CategoryID = new SelectList(db.Categories.ToList(), "CategoryID", "Name", product.CategoryID);
            return View(product);
        }

        //
        // GET: /Products/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Product product = db.Products.First(p => p.ID == id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Products/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Product product = db.Products.First(p => p.ID == id);
            db.CreateObjectSet<Product>().Attach(product);
            db.ObjectStateManager.ChangeObjectState(product, EntityState.Deleted);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

第3、视图
视图结构:
下面是视图代码:
Index:
@model IEnumerable<TMVC.DAL.Product>
@{
    ViewBag.Title = "Index";
}
<h2>
    产品页面</h2>
<p>@Html.ActionLink("添加", "Create")</p>
<table>
    <tr>
        @*<th>@Html.DisplayNameFor(model => model.Name)
        </th>
        <th>@Html.DisplayNameFor(model => model.CategoryID)
        </th>
        <th>@Html.DisplayNameFor(model => model.UnitPrice)
        </th>
        <th>@Html.DisplayNameFor(model => model.UnitsInStock)
        </th>*@
        <th>
            名称
        </th>
        <th>
            类别
        </th>
        <th>
            价格
        </th>
        <th>
            库存
        </th>
        <th>
            编辑
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(mi => item.Name)
            </td>
            <td>@Html.DisplayFor(mi => item.CategoryID)
            </td>
            <td>@Html.DisplayFor(mi => item.UnitPrice)
            </td>
            <td>@Html.DisplayFor(mi => item.UnitsInStock)
            </td>
            <td>@Html.ActionLink("编辑", "Edit", new { id = item.ID }) |
                @Html.ActionLink("详细", "Details", new { id = item.ID }) | @Html.ActionLink("删除", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
</table>

Create:

@model TMVC.DAL.Product
@{
    ViewBag.Title = "Create";
}
<h2>
    添加</h2>
@using (Html.BeginForm())
{ 
    @Html.ValidationSummary(true);
    <fieldset>
        <legend>产品</legend>
        <div class="editor-label">
            名称 @* @Html.LabelFor(model => model.Name)*@
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            类别 @* @Html.LabelFor(model => model.CategoryID, "CategoryPCategor")*@
        </div>
        <div class="editor-field">
            @*@Html.DropDownList("CategoryID", String.Empty)*@
            @Html.EditorFor(model => model.CategoryID)
            @Html.ValidationMessageFor(model => model.CategoryID)
        </div>
        <div class="editor-label">
            价格 @*@Html.LabelFor(model => model.UnitPrice)*@
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UnitPrice)
            @Html.ValidationMessageFor(model => model.UnitPrice)
        </div>
        <div class="editor-label">
            库存@* @Html.LabelFor(model => model.UnitsInStock)*@
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UnitsInStock)
            @Html.ValidationMessageFor(model => model.UnitsInStock)
        </div>
        <p>
            <input type="submit" value="确定添加" />
        </p>
    </fieldset>
}

Delete:

@model TMVC.DAL.Product
@{
    ViewBag.Title = "Delete";
}
<h2>
    删除</h2>
<h3>
    你确定要删除这个产品吗?</h3>
<fieldset>
    <legend>产品</legend>
    <div class="display-label">
        名称
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
    <div class="display-label">
        类别
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
    <div class="display-label">
        价格
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.UnitPrice)
    </div>
    <div class="display-label">
        库存
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.UnitsInStock)
    </div>
</fieldset>
@using (Html.BeginForm())
{
    <p>
        <input type="submit" value="删除" />
        |
        @Html.ActionLink("返回产品列表", "Index")
    </p>
}

Details:

@model TMVC.DAL.Product
@{
    ViewBag.Title = "Details";
}
<h2>
    详细</h2>
<fieldset>
    <legend>产品</legend>
    <p>
        名称:@Html.DisplayFor(model => model.Name)</p>
    <p>
        类别:@Html.DisplayFor(model => model.CategoryID)</p>
    <p>
        价格:@Html.DisplayFor(model => model.UnitPrice)</p>
    <p>
        库存:@Html.DisplayFor(model => model.UnitsInStock)</p>
</fieldset>
<p>@Html.ActionLink("编辑", "Edit", new { id = Model.ID }) | @Html.ActionLink("返回", "Index")</p>

Edit:

@model TMVC.DAL.Product
@{
    ViewBag.Title = "Edit";
}
<h2>
    编辑</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>产品</legend>
        @Html.HiddenFor(model => model.ID)
        <div class="editor-label">
            名称
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            类别
        </div>
        <div class="editor-field">
            @*@Html.DropDownList("CategoryID", String.Empty)*@
            @Html.EditorFor(model => model.CategoryID)
            @Html.ValidationMessageFor(model => model.CategoryID)
        </div>
        <div class="editor-label">
            价格
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UnitPrice)
            @Html.ValidationMessageFor(model => model.UnitPrice)
        </div>
        <div class="editor-label">
            库存
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UnitsInStock)
            @Html.ValidationMessageFor(model => model.UnitsInStock)
        </div>
        <p>
            <input type="submit" value="保存" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("返回产品列表", "Index")
</div>
RouteConfig
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );


 


 
原文地址:https://www.cnblogs.com/houzuofeng/p/3622496.html