前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MVC Code First (代码优先)

MVC Code First (代码优先)

作者头像
全栈程序员站长
发布2022-07-06 16:51:17
8850
发布2022-07-06 16:51:17
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君

首先配置web.config

代码语言:javascript
复制
  <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类
代码语言:javascript
复制
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类
代码语言:javascript
复制
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
    {
        /// <summary>
        /// 表示用于运行创建、读取、更新和删除操作的类型化实体集。DbSet 不是公共可构造的。仅仅能从 System.Data.Entity.DbContext实例创建。        /// </summary>        public DbSet<Book> Books { get; set; }    }}

加入一个Book控制器

要了解FormCollection请參考:FormCollection传值

代码语言:javascript
复制
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() 
        {
            //这是一个简单的Linq查询,在对数据库进行操作时。EF会检查当前的数据连接指定的数据库是否被创建,假设没有则有EF负责依据实体模型类创建数据库、数据表;假设存在,EF会将查询条件加入到Sql查询语句,再将Sql语句发送到数据库进行数据读取。在完毕数据读取后,将数据转换为实体对象集合。EF对数据库的操作大致如此            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 所以我们能够通过该属性来推断数据的有效性,但有时在数据验证时有时我们不须要验证全部的数据,比方登录时仅仅须要验证username及password格式是否输入正确就可以。使用下面方法能够排除要验证的字段:ModelState.Remove("Email");不验证Email。这样Email这个字段就不会被验证了,Email验证不通过ModelState.IsValid的值仍然是true            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) //事实上这的FormCollection c 换成 int a=5 或者 int a=6 都是能够的。仅仅要保证这个Delete方法与上面的Delete方法參数不同就能够了。事实上也就是保证两个方法构成重载        {            //Find()是返回满足条件的第一个元素,假设没有该元素,则返回null。            Book book = db.Books.Find(id); //也能够写成:Book book=db.Books.FirstOrDefault(d=>d.BookID==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 视图 首页
代码语言:javascript
复制
@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
代码语言:javascript
复制
@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
代码语言:javascript
复制
@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
代码语言:javascript
复制
@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
代码语言:javascript
复制
@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>
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)
MVC Code First (代码优先)

版权声明:本文博主原创文章。博客,未经同意不得转载。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116945.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 首先配置web.config
  • 然后在Model里加入一个Book 类和一个BookDbContext类
    • Book类
      • BookDbContext类
      • 加入一个Book控制器
      • view
        • Index 视图 首页
          • Create
            • Delete
              • Edit
                • Details
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档