MVC Code First

首先配置好web.config

  <connectionStrings>
    <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;"
     providerName="System.Data.SqlClient" />
  </connectionStrings>

然后在Model里添加一个Book 类和一个BookDbContext类

Book类

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

namespace MvcApplication3.Models
{
    public class Book
    {
        public int BookID { get; set; }
        public string BookName { get; set; }
        public string Author { get; set; }
        public string Publisher { get; set; }
        public decimal Price { get; set; }
        public string Remark { get; set; }
    }
}

BookDbContext类

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

namespace MvcApplication3.Models
{
    /// <summary>
    /// BookDbContext代表EF中Book在数据库中的上下文对象,通过DbSet<Book>使实体类与数据库关联起来。Books属性表示数据库中的数据集实体,用来处理数据的存取与更新。BookDbContext派生自DbContext,需要添加System.Data.Entity的引用。
    /// </summary>
    public class BookDbContext:DbContext
    {
        public DbSet<Book> Books { get; set; }
    }
}

添加一个Book控制器

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

namespace MvcApplication3.Controllers
{
    public class BookController : Controller
    {
        //
        // GET: /Book/

        BookDbContext db = new BookDbContext();

        /// <summary>
        /// //查询出所有的Book对象,组成一个Books,让它展示在页面首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var books = from b in db.Books
                        select b;
            return View(books.ToList());
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Book book)
        {

            //MVC验证中所有属性验证成功ModelState.IsValid等于true,只要有一个验证不成功ModelState.IsValid就等于false 所以我们可以通过该属性来判断数据的有效性,但有时在数据验证时有时我们不需要验证所有的数据,比如登录时只需要验证用户名及密码格式是否输入正确即可。

            if (ModelState.IsValid)
            {
                db.Books.Add(book);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                return View(book);
            }

        }
        [HttpGet]
        public ActionResult Delete(int id)
        {
            var data = from DataItem in db.Books
                       where DataItem.BookID == id
                       select DataItem;
            ViewData.Model = data.Single();
            return View();
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection c)
        {
            //Find()是返回满足条件的第一个元素,如果没有该元素,则返回null。
            Book book = db.Books.Find(id);
            db.Books.Remove(book);
            db.SaveChanges();
            return RedirectToAction("Index");

        }

        public ActionResult Edit(int id)
        {
            //var data = from dataitem in db.Books
            //           where dataitem.BookID == id
            //           select dataitem;
            //ViewData.Model = data.Single();
            //return View();

            //Find()是返回满足条件的第一个元素(即:Books中 BookID的的值为id的Book),如果没有该元素,则返回null。
            Book book = db.Books.Find(id);
            if (book == null)
            {
                return RedirectToAction("Index");
            }
            return View(book);

        }
        [HttpPost]
        public ActionResult Edit(Book newbook)
        {
            try
            {
                Book oldbook = db.Books.Find(newbook.BookID);

                //使用来自控制器的当前值提供程序的值更新指定的模型实例
                UpdateModel(oldbook);

                //将在此上下文中所做的所有更改保存到基础数据库。
                db.SaveChanges();
                return RedirectToAction("Index");

            }
            catch (Exception ex)
            {
                //AddModelError:将指定的错误消息添加到与指定键关联的模型状态字典的错误集合中。
                ModelState.AddModelError("", "修改失败,请查看详细错误信息" + ex.Message + ex.StackTrace);
            }
            return View(newbook);
        }

        public ActionResult Details(int id)
        {
            //Find()是返回满足条件的第一个元素(即:Books中 BookID的的值为id的Book),如果没有该元素,则返回null。
            Book book = db.Books.Find(id);
            if (book == null)
            {
                return RedirectToAction("Index");
            }
            return View(book);
        }

    }
}

view

Index 视图 首页

@model IEnumerable<MvcApplication3.Models.Book>
@{
    ViewBag.Title = "图书列表-MvcBook";
}
<h2>
    图书列表</h2>
<p>
    @Html.ActionLink("增加图书", "Create")
</p>
<table>
    <tr>
        <th>图书名称</th><th>作者</th><th>出版社</th><th>价格</th><th>备注</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.BookName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Author)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Publisher)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Remark)
            </td>
            <td>
                @Html.ActionLink("编辑", "Edit", new { id = item.BookID }) |
                @Html.ActionLink("详细", "Details", new { id = item.BookID }) |
                @Html.ActionLink("删除", "Delete", new { id = item.BookID })
            </td>
        </tr>
    }
</table>

Create

@model MvcApplication3.Models.Book

@{
    ViewBag.Title = "Create";
}

<h2>增加</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Book</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.BookName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BookName)
            @Html.ValidationMessageFor(model => model.BookName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Author)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Author)
            @Html.ValidationMessageFor(model => model.Author)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Publisher)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Publisher)
            @Html.ValidationMessageFor(model => model.Publisher)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Remark)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Remark)
            @Html.ValidationMessageFor(model => model.Remark)
        </div>

        <p>
            <input type="submit" value="增加" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("跳转到首页", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Delete

@model MvcApplication3.Models.Book

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>Book</legend>

    <table>
    <tr><th>图书名称:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>
    <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>
    <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>
    <tr><th>价格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>
    <tr><th>备注</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>
    </table>

</fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="删除" /> |
        @Html.ActionLink("跳转到首页", "Index")
    </p>
}

Edit

@model MvcApplication3.Models.Book

@{
    ViewBag.Title = "Edit";
}

<h2>编辑</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Book</legend>

        @Html.HiddenFor(model => model.BookID)

        <div class="editor-label">
            @Html.LabelFor(model => model.BookName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BookName)
            @Html.ValidationMessageFor(model => model.BookName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Author)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Author)
            @Html.ValidationMessageFor(model => model.Author)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Publisher)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Publisher)
            @Html.ValidationMessageFor(model => model.Publisher)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Remark)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Remark)
            @Html.ValidationMessageFor(model => model.Remark)
        </div>

        <p>
            <input type="submit" value="保存" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("跳转到首页", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Details

@model MvcApplication3.Models.Book

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Book</legend>
    <table>
    <tr><th>图书名称:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>
    <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>
    <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>
    <tr><th>价格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>
    <tr><th>备注</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>
    </table>
</fieldset>
<p>
    @Html.ActionLink("编辑", "Edit", new { id=Model.BookID }) |
    @Html.ActionLink("跳转到首页", "Index")
</p>
时间: 2024-10-10 09:44:34

MVC Code First的相关文章

ASP.NET MVC Code First 遇到的问题及解决方法

照抄大牛的Demo,自己信心满满地建好个各种项,结果死活不让通过,遇到了以下几个问题(大部分是自己作出来的...) 1.运行不起来,报错如下Error 26: SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 各种百度都是不行,后来看了一下,WebConfig的连接字符串是新加而

MVC Code First (代码先行)

首先配置好web.config [html] view plain copy <connectionStrings> <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;" providerName="Sy

MVC Code First 自动生成数据库时生成的表名会多了一个s

如图:我的类文件都是不带s的 但是生成了的数据库表却是带了s的,如下图: 因为code first默认了就会加上s,解决方法: 在上下文文件中加入这段代码: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } 如图所示:

Entity Framework mvc Code First data migration

1. Code First 可以先在代码里写好数据模型,自动生成DB.下一次启动的时候会根据__MigrationHistory判断 数据库是否和模型一致. 详情参考:http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx 如果想改变数据库的某个字段,而又不想重新生成一遍数据库的话.请按照以下操作做: Package Manager console: enabl

MVC Code First (代码优先)

首先配置web.config <connectionStrings> <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;" providerName="System.Data.SqlClient"

asp.net mvc code first 在本地数据库中生成数据库

新手刚开始接触 Entity FrameWork. 网上看到的列子大多都是在web.config中这么添加: <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.Sql

mvc code first模式学习模板

第一步  新建mvc项目 第二步  在models下面新建模型利类 public class Product { public int ID { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } } 第三步 新建数据库上下文类(Models文件夹下) public class EFDbContext : DbContex

MVC Code First 当实体类发生变化时,如何自动更新数据库表

下面做一个例子,Category是用户新建的一个实体类,然后添加一个字段,然后让数据库中的Category表也添加一个字段 1.Category.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace BlogAppDAL.Entities { public clas

asp.net MVC code first Migrations : Model 同步到DB中

找来找去,看来用这个功能的人很少. http://www.it165.net/pro/html/201403/10653.html 步骤: 1,在程序包管理控制台上,Enable-Migrations,注意选择dbcontext. 2,add-migration AddRatingMig 3,update-database. 注意2步和3步的顺序,做不好就关闭开发环境后再试一试.