博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
3.EF 6.0 Code-First实现增删查改
阅读量:6939 次
发布时间:2019-06-27

本文共 17836 字,大约阅读时间需要 59 分钟。

原文链接:

或者:

系列目录:

 

  • 【在MVC中使用泛型仓储模式和工作单元来做增删查改】

 

本来不想写这篇的,因为感觉增删查改,实在是太Easy了。好了,为了巩固学习,还是继续吧:

打算实现书籍的增删查改,有两个实体,一个是Book【书籍实体】,另外一个是出版商实体【Publisher】,一个出版商可以出版很多书籍,一本书只能是由一个出版商出版。所以,书籍和出版商之间是一对多的关系。

先来看看整个项目的结构吧:

 

Entity实体中:

BaseEntity实体:【日期使用了数据注解,这样在显示的时候,就有格式了。】

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF.Entity{   public abstract class BaseEntity    {       ///        /// ID       ///        public int ID { get; set; }       ///        /// 添加时间       ///        ///        [DataType(DataType.Date)]       [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]       public DateTime AddedDate { get; set; }       ///        /// 修改时间       ///        ///         [DataType(DataType.Date)]        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]       public DateTime ModifiedDate { get; set; }    }}

 

 Book实体:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF.Entity{    ///     /// Book实体    ///     public class Book:BaseEntity    {        ///         /// 书名        ///         public string BookName { get; set; }        ///         /// 书的作者        ///         public string BookAuthor { get; set; }        ///         /// 书的价格        ///         public decimal BookPrice { get; set; }        ///         /// 出版商编号        ///         public int PublisherId { get; set; }        ///         /// 导航属性---出版商        ///         public virtual Publisher Publisher { get; set; }    }}

 

出版商实体:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EF.Entity{   public class Publisher:BaseEntity    {       ///        /// 出版商的名字       ///        public string PublisherName { get; set; }       ///        /// 导航属性       ///        public virtual ICollection
Books { get; set; } }}

 

然后在EF.Data项目中:

BookMap类:

using EF.Entity;using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF.Data{    public class BookMap:EntityTypeConfiguration
{ public BookMap() { //配置主键 this.HasKey(s => s.ID); //配置字段 this.Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(s => s.BookName).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); // this.Property(s => s.BookAuthor).HasColumnType("nvarchar(50)").IsRequired();//注意这个和BookName字段配置的区别之处:这样写EF生成不了数据库 this.Property(s => s.BookAuthor).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); this.Property(s => s.BookPrice).IsRequired(); this.Property(s => s.AddedDate).IsRequired(); this.Property(s => s.ModifiedDate).IsRequired(); this.Property(s => s.PublisherId).IsRequired(); //配置关系[一个出版商可以出版很多书籍]【外键单独配置,不是必须在Property中配置,当然也可以在Property中配置】 this.HasRequired(s => s.Publisher).WithMany(s => s.Books).HasForeignKey(s => s.PublisherId).WillCascadeOnDelete(true); //配置表名字 this.ToTable("Books"); } }}

PublisherMap类:

using EF.Entity;using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF.Data{   public class PublisherMap:EntityTypeConfiguration
{ public PublisherMap() { //配置主键 this.HasKey(s => s.ID); this.Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); // this.Property(s => s.PublisherName).HasColumnType("nvarchar(50)").IsRequired();//这样写,有问题,生成不了数据库 this.Property(s => s.PublisherName).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); this.Property(s => s.AddedDate).IsRequired(); this.Property(s => s.ModifiedDate).IsRequired(); } }}

 

出版商我这里不做增删查改,到时候手动添加几条数据进去,然后在Book的视图中,把出版商做成下拉框的样式:所以我这里额外添加一个实体:【PublisherModel实体中的构造函数里的初始化属性嗲吗,不能忘记!!!】

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Web;using System.Web.Mvc;namespace EF.Web.Models{    public class PublisherModel    {        public PublisherModel()        {            PublisherList = new List
(); } [Display(Name="PublisherName")] public int PublisherID { get; set; } public List
PublisherList { get; set; } }}

 

数据上下文类:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Data.Entity.ModelConfiguration;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace EF.Data{   public class EFDbContext:DbContext    {       public EFDbContext()           : base("name=DbConnectionString")       {               }       protected override void OnModelCreating(DbModelBuilder modelBuilder)       {           var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()        .Where(type => !String.IsNullOrEmpty(type.Namespace))        .Where(type => type.BaseType != null && type.BaseType.IsGenericType             && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));           foreach (var type in typesToRegister)           {               dynamic configurationInstance = Activator.CreateInstance(type);               modelBuilder.Configurations.Add(configurationInstance);           }             //base.OnModelCreating(modelBuilder);       }    }}

Ef.Data项目和Web项目中都要加上连接字符串:

 

现在看看Web项目:

using EF.Data;using EF.Entity;using EF.Web.Models;using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Web;using System.Web.Mvc;namespace EF.Web.Controllers{    public class BookController : Controller    {        private EFDbContext db;        public BookController()        {            db = new EFDbContext();        }        #region 列表        ///         /// 列表        ///         /// 
public ActionResult Index() { return View(db.Set
().ToList()); } #endregion #region AddBook ///
/// 添加Book /// ///
public ActionResult AddBook() { PublisherModel model = new PublisherModel(); List
listPublisher = db.Set
().ToList(); foreach (var item in listPublisher) { model.PublisherList.Add(new SelectListItem() { Text = item.PublisherName, Value = item.ID.ToString() }); } ViewBag.PublishedList = model.PublisherList; return View(); } ///
/// 添加Book /// ///
[HttpPost] public ActionResult AddBook([Bind(Include = "BookName,BookAuthor,BookPrice,AddedDate,ModifiedDate,PublisherId")] Book model) { Book addBook = new Book() { AddedDate=model.AddedDate, BookAuthor=model.BookAuthor, BookName=model.BookName, BookPrice=model.BookPrice, ModifiedDate=model.ModifiedDate, PublisherId = Convert.ToInt32( Request["PublishedName"].ToString()) //这里因为出版商我用的是另外的Model,视图中使用模型绑定只能用一个Model,所以修改和添加只能这样搞了。 }; db.Entry(addBook).State = EntityState.Added; db.SaveChanges(); return RedirectToAction("Index"); } #endregion #region UpdateBook ///
/// 修改Book /// ///
///
public ActionResult UpdateBook(int bookId) { PublisherModel model = new PublisherModel(); List
listPublisher = db.Set
().ToList(); foreach (var item in listPublisher) { model.PublisherList.Add(new SelectListItem() { Text = item.PublisherName, Value = item.ID.ToString() }); } ViewBag.PublishedList = model.PublisherList; Book bookModel = db.Set
().Where(s => s.ID == bookId).FirstOrDefault(); return View(bookModel); } ///
/// 修改Book /// ///
///
[HttpPost] public ActionResult UpdateBook([Bind(Include = "ID,BookName,BookAuthor,BookPrice,AddedDate,ModifiedDate,PublisherId")] Book model) //注意这里一定别忘记绑定 ID列哦 { Book bookModel = db.Set
().Where(s => s.ID == model.ID).FirstOrDefault(); if (bookModel != null) { Book updatemodel = new Book() { AddedDate = model.AddedDate, BookAuthor = model.BookAuthor, ID = model.ID, ModifiedDate = model.ModifiedDate, BookName = model.BookName, BookPrice = model.BookPrice, PublisherId = Convert.ToInt32(Request["PublishedName"].ToString())//这里因为出版商我用的是另外的Model,视图中使用模型绑定只能用一个Model,所以修改和添加只能这样搞了。 }; db.Entry(bookModel).CurrentValues.SetValues(updatemodel); //保存的另外一种方式 db.SaveChanges(); return RedirectToAction("Index"); } else { return View(model); } #region 保存的方式二 //db.Entry(model).State = EntityState.Modified; //db.SaveChanges(); //return RedirectToAction("Index"); #endregion } #endregion #region DeleteBook public ActionResult DeleteBook(int bookId) { Book model = db.Set
().Where(s => s.ID == bookId).FirstOrDefault(); return View(model); } [HttpPost] public ActionResult DeleteBook(int bookId, FormCollection form) { Book model = db.Set
().Where(s => s.ID == bookId).FirstOrDefault(); db.Entry(model).State = EntityState.Deleted; db.SaveChanges(); return RedirectToAction("Index"); } #endregion }}

 

视图代码,我使用MVC模板生成:【适当做修改】

AddBook视图:

@model EF.Entity.Book@{    ViewBag.Title = "AddBook";}

AddBook

@using (Html.BeginForm("AddBook","Book",FormMethod.Post)) { @Html.AntiForgeryToken()

Book


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.AddedDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.AddedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.AddedDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ModifiedDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookAuthor, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookAuthor, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookAuthor, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookPrice, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookPrice, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookPrice, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.PublisherId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("PublishedName", ViewData["PublishedList"] as List
) @*@Html.EditorFor(model => model.PublisherId, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.ValidationMessageFor(model => model.PublisherId, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")

UpdateBook视图:

@model EF.Entity.Book@{    ViewBag.Title = "UpdateBook";}

UpdateBook

@using (Html.BeginForm("UpdateBook","Book",FormMethod.Post)){ @Html.AntiForgeryToken()

Book


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ID)
@Html.LabelFor(model => model.AddedDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.AddedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.AddedDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ModifiedDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookAuthor, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookAuthor, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookAuthor, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.BookPrice, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.BookPrice, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookPrice, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.PublisherId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("PublishedName", ViewData["PublishedList"] as List
) @*@Html.EditorFor(model => model.PublisherId, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.ValidationMessageFor(model => model.PublisherId, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")

注意:这里我只是把有改动的视图贴了出来,其他的视图,根据MVC模板生成之后,就不用管了。

@model IEnumerable
@{ ViewBag.Title = "Index";}

Index

@Html.ActionLink("Create New", "AddBook")

@foreach (var item in Model) {
}
@Html.DisplayNameFor(model => model.AddedDate) @Html.DisplayNameFor(model => model.ModifiedDate) @Html.DisplayNameFor(model => model.BookName) @Html.DisplayNameFor(model => model.BookAuthor) @Html.DisplayNameFor(model => model.BookPrice) @Html.DisplayNameFor(model => model.PublisherId)
@Html.DisplayFor(modelItem => item.AddedDate) @Html.DisplayFor(modelItem => item.ModifiedDate) @Html.DisplayFor(modelItem => item.BookName) @Html.DisplayFor(modelItem => item.BookAuthor) @Html.DisplayFor(modelItem => item.BookPrice) @Html.DisplayFor(modelItem => item.PublisherId) @Html.ActionLink("Edit", "UpdateBook", new { bookId = item.ID }) | @Html.ActionLink("Details", "DetailsBook", new { bookId = item.ID }) | @Html.ActionLink("Delete", "DeleteBook", new { bookId = item.ID })

效果图:

 

 

 

 总结:1.下拉框实体中,构造函数初始化语句不能忘记。

2.修改的方式,有新变化看代码;

3.模型绑定的时候,特别要注意,Bind的字段,修改的时候,Bind字段ID不能少。

 

转载地址:http://ahinl.baihongyu.com/

你可能感兴趣的文章
IE block my cookie in iframe
查看>>
02课后作业
查看>>
初识单片机(51单片机学习之旅系列)
查看>>
linux配置java jdk
查看>>
python全栈开发从入门到放弃之socket并发编程之IO模型
查看>>
ECMAScript 5 —— 执行环境及作用域
查看>>
Python:程序发布方式简介一(打包为可执行文件EXE)
查看>>
Kdevelop简单应用以及调试
查看>>
【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限
查看>>
自己的第一个网页
查看>>
jquery文本框textarea自适应高度
查看>>
三星泰泽Tizen系统挑战Android系统
查看>>
关于TalkHelper Screen Record软件分析
查看>>
真心老了,记性下降太快了,有些东西还是需要用文字记录下来
查看>>
java算法 第七届 蓝桥杯B组(题+答案) 8.四平方和
查看>>
Eclipse(PDT) + Xdebug
查看>>
文本内容超出父元素一行或多行省略号代替
查看>>
冒泡排序法
查看>>
第五次作业
查看>>
创建外部用户_外部表
查看>>