第2章 Entity Framework——ASP.NET MVC企业级实战 痛定思痛。 2021-06-24 16:11 410阅读 0赞 使用工具:sql server 2012,vs2017 由于书籍中使用的sql server,所以在本书的学习中使用的数据库为sql servier 2012。学习之前,先将书籍中利用到的数据库附加进去。 数据分享:northwnd 链接:[https://pan.baidu.com/s/1i6FSRlj][https_pan.baidu.com_s_1i6FSRlj] 密码:fuh7 ## 目录 ## #### 1.DBFirst #### #### 2 Entity Framework增删改查 #### #### 3 LINQ To EF #### #### 4 Code First 开发方式 #### #### 1.DBFirst #### * 首先添加实体模型(ado.net 实体数据模型),一路安装下去就可以了,并不会像连接mysql一样会遇到各种各样的问题。 ![2789632-7dd1637999bd035c.png][] * 验证安装情况 通过edmx可以看到,几张表已经加载进来了 ![2789632-156fcd0dbfeb621e.png][] 然后通过调试再来看看数据情况,尝试从orders表中查询id为10248的订单数据: ![2789632-deecb41453d73364.png][] 由上图,可见对应的那条数据已经被查出来了。 #### 2 Entity Framework增删改查 #### ###### 2.1 新增 ###### 在这里可以留意下方法二DbEntityEntry的使用,由于这里面的Order在数据库中有了限制,虽然设置11090,实际加入进去的还是递增1的数据加入。 ![2789632-dd35dd86e5e46423.png][] ###### 2.2根据条件排序和查询 ###### 使用以下的方式进行查询,需要先引入**System.Linq.Expressions;** 使用这种方式,需要先了解下Experssion的以及lambda的使用方式。 方法代码: #region 测试根据条件排序和查询 public static List<Customers> GetListBy<Tkey>(Expression<Func<Customers, bool>> whereLambda, Expression<Func<Customers, Tkey>> orderLambda) { using (NorthwindEntities entity = new NorthwindEntities()) { return entity.Customers.Where(whereLambda).OrderBy(orderLambda).ToList(); } } #endregion 调用方式: static void Main(string[] args) { Expression<Func<Customers, bool>> whereLambda = (Customers) => Customers.CustomerID == "alen"; Expression<Func<Customers, string>> orderLambda = (Customers) => Customers.CustomerID; var result = FunctionMethods.GetListBy<string>(whereLambda,orderLambda); } 调用结果: ![2789632-acb5ddcd24f61d60.png][] ###### 2.3 分页查询 ###### 方法代码: #region 分页查询 public static List<Customers> GetPagedList<Tkey>(int pageIndex, int pageSize, Expression<Func<Customers, bool>> whereLambda, Expression<Func<Customers, Tkey>> orderLambda) { using (NorthwindEntities entity = new NorthwindEntities()) { return entity.Customers.Where(whereLambda).OrderBy(orderLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } #endregion 调用方式: //分页查询 Expression<Func<Customers, bool>> whereLambda = (Customers) => Customers.CustomerID.Length < 4; Expression<Func<Customers, string>> orderLambda = (Customers) => Customers.CustomerID; int pageIndex = 1; int pageSize = 10; var result = FunctionMethods.GetPagedList(pageIndex,pageSize,whereLambda,orderLambda); 调用结果: ![2789632-f2de97713f64b5f7.png][] ###### 2.4 修改 ###### 方法代码: #region 修改 public static void Edit() { using (NorthwindEntities entiy = new NorthwindEntities()) { Customers _Customer = entiy.Customers.Where(x => x.CustomerID == "alen").FirstOrDefault(); Console.WriteLine("修改前:" + _Customer.ContactName); _Customer.ContactName = "张中华"; entiy.SaveChanges(); Console.WriteLine("修改成功:" + _Customer.ContactName); Console.ReadLine(); } } #endregion 调用方式: //修改 FunctionMethods.Edit(); 调用结果: ![2789632-cf9c987a0d8f61cd.png][] 这个地方修改的速度有点慢啊,打印下看看用了多久…… 不是吧,用了那么久,798ms,修改一条记录竟然用了798ms。 ![2789632-b1dbeb8b1c1ef4f2.png][] 用时统计 我们再来看看查询用了多久: 这个时候并不清楚为什么用时降了下来,但是确实查询确实是占了很大的一段的时间的。 ![2789632-9c8463c1f4c60794.png][] 我们再看看是不是由于EF查询的速度跟不上,使用SQL进行查询: 方法代码: public static void EditBySql() { using (NorthwindEntities entity = new NorthwindEntities()) { DateTime d1 = DateTime.Now; string sql = "select top 1 * from Northwind.dbo.Customers where CustomerID = 'alen'"; var result = entity.Database.SqlQuery<Customers>(sql); Console.WriteLine("修改前:" + result.FirstOrDefault().ContactName); DateTime d3 = DateTime.Now; Console.WriteLine("查询用时:" + (d3 - d1).Milliseconds + "ms"); string sqlUpdate = "update Northwind.dbo.Customers set ContactName = '小小张' where CustomerID = 'alen'"; var result1 = entity.Database.ExecuteSqlCommand(sqlUpdate); Console.WriteLine("修改成功:" + result1); DateTime d2 = DateTime.Now; Console.WriteLine("共用时:" + (d2 - d1).Milliseconds + "ms"); Console.ReadLine(); } } ![2789632-ffb31542fba8875c.png][] ![2789632-8f4a5eff7e802bcd.png][] 根据EF查询最快用时,还是比直接使用sql慢100ms左右的。这个地方做了两次测试,可见直接使用sql进行查询要比EF还是快得多的,将近一半用时左右。 #### 3 LINQ To EF #### 方法代码: #region LINQ To EF public static void LINQToEF() { using (NorthwindEntities entity = new NorthwindEntities()) { //简单查询 var result = from c in entity.Customers select c; Console.WriteLine("简单查询,第一条数据ContactName" + result.FirstOrDefault().ContactName); //条件查询 //普通linq写法 var result1 = from c in entity.Customers where c.CustomerID.Length > 0 select c; Console.WriteLine("条件查询:普通linq写法,第一条数据ContactName:" + result1.FirstOrDefault().ContactName); //Lambda表达式写法 var result2 = entity.Customers.Where(x => x.CustomerID.Length > 0).ToList(); Console.WriteLine("条件查询:Lambda表达式写法,第一条数据ContactName:" + result2.FirstOrDefault().ContactName); //排序分页 IQueryable<Customers> result3 = (from c in entity.Customers orderby c.CustomerID select c).Skip(0).Take(10); Console.WriteLine("排序分页:第一条数据ContactName:" + result3.FirstOrDefault().ContactName); //连接 var query = from d in entity.Order_Details join order in entity.Orders on d.OrderID equals order.OrderID select new { OrderId = order.OrderID, ProductId = d.ProductID, UnitPrice = d.UnitPrice }; foreach (var q in query.Take(5)) { Console.WriteLine("{0},{1},{2}",q.OrderId,q.ProductId,q.UnitPrice); } Console.ReadLine(); } } ![2789632-9861ae37028857f7.png][] image.png #### 4 Code First 开发方式 #### 优势: * 开发简介 * 效率提高 * 自动化程度提高 * 可适用于原有老项目 劣势: * 性能不好 * 了解的人比较少 * 学习成本高,对开发人员的要求相对较高 ###### 4.1创建Code First Demo ###### * 1 新建ASP.NET MVC4 Web 应用程序,项目模版选择“空” * 2 引入程序集EntityFramework和System.Data.Entity * 3在Models文件加下面新建Order.cs和OrderDetail.cs模型类文件 Order代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace CodeFirstDemo.Models { public class Order { /// <summary> /// 属性名后面有Id,默认会当成主键,可以不用添加[Key]属性 /// </summary> [Key] public int OrderId { get; set; } /// <summary> /// 订单号 /// </summary> [StringLength(50)] public string OrderCode { get; set; } /// <summary> /// 订单金额 /// </summary> public decimal OrderAmount { get; set; } /// <summary> /// 导航属性设置成virtual,可以实现延迟加载 /// </summary> public virtual ICollection<OrderDetail> OrderDetail { get; set; } } } OrderDetail代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CodeFirstDemo.Models { public class OrderDetail { [Key] public int OrderDetailId { get; set; } /// <summary> /// 订单明细单价 /// </summary> public decimal Price { get; set; } /// <summary> /// 订单明细数量 /// </summary> public int Count { get; set; } /// <summary> /// 外键,如果属性名称和Order主键名称一样,默认会当成外键,可以不加ForeignKey特性 /// </summary> [ForeignKey("OrderBy")] public int OrderId { get; set; } /// <summary> /// 导航属性 /// </summary> public virtual Order OrderBy { get; set; } } } * 4 在配置文件中写连接字符串 <connectionStrings> <add name="CodeFirstDemoModel" connectionString="server=.;database=CodeFirstDamo;uid=sa;pwd=Password" providerName="System.Data.SqlClient"/> </connectionStrings> * 5 创建上下文 using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace CodeFirstDemo.Models { public class CodeFirstContext:DbContext { /// <summary> /// 注意这里的name要和配置文件里面配置的上下文连接字符串名称一致 /// </summary> public CodeFirstContext() : base("name=CodeFirstContext") { } public DbSet<Order> Order { get; set; } public DbSet<OrderDetail> OrderDetail { get; set; } } } * 6 在controller层创建一个homecontroller然后进行创建数据库。 ![2789632-0f39109fa10f8a6e.png][] HomeController.cs代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CodeFirstDemo.Models; namespace CodeFirstDemo.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { CodeFirstContext db = new CodeFirstContext(); db.Database.CreateIfNotExists(); return View(db.Order.ToList()); } } } 在这里并没有像书上写的那么使用,之后再看为什么把db写成一个属性使用。 Home/Index.cshtml代码 @{ ViewBag.Title = "Index"; } <h2>Index</h2> 调试运行 ![2789632-6928acdeb20133e0.png][] 此时,在界面上并没有体现关于数据库相关的显示。但是可以在SQL Server中查看代码是否已经执行: ![2789632-59a7135c0f19bb81.png][] 所以在Controller中的代码还是执行完成的。 微信公众号: ![2789632-3b18269684ea9294.png][] 公众号.png [https_pan.baidu.com_s_1i6FSRlj]: https://pan.baidu.com/s/1i6FSRlj [2789632-7dd1637999bd035c.png]: /images/20210615/51fb6e02ab884fd487828048f22ad8f8.png [2789632-156fcd0dbfeb621e.png]: /images/20210615/93785cf1badf43a5bc90030e92fd3919.png [2789632-deecb41453d73364.png]: /images/20210615/9e2146baae774e3fb58f77bb9e7a1173.png [2789632-dd35dd86e5e46423.png]: /images/20210615/9940ae13c12042f7b203996d56f758cb.png [2789632-acb5ddcd24f61d60.png]: /images/20210615/6d2a0b547e874d848baf9a97cff6c850.png [2789632-f2de97713f64b5f7.png]: /images/20210615/84ae404e982747258a25e75828c47730.png [2789632-cf9c987a0d8f61cd.png]: /images/20210615/1dac1ae4daa5494598386c9ce0a44dcf.png [2789632-b1dbeb8b1c1ef4f2.png]: /images/20210615/c2506ad7bbb3482399e5a2e6ac36c1c7.png [2789632-9c8463c1f4c60794.png]: /images/20210615/5359d4cd0f2f4292acca5d5f1a38e3b3.png [2789632-ffb31542fba8875c.png]: /images/20210615/6358e6da730e446ab357c36577f49cca.png [2789632-8f4a5eff7e802bcd.png]: /images/20210615/cb643c08d9014f4bbca154d059290c95.png [2789632-9861ae37028857f7.png]: /images/20210615/7754390c7dee4d1cb548b4cc8e652eea.png [2789632-0f39109fa10f8a6e.png]: /images/20210615/6d2a770286df482995bc01b8e47d8ed3.png [2789632-6928acdeb20133e0.png]: /images/20210615/68363db23a9644268a850693dc82a757.png [2789632-59a7135c0f19bb81.png]: /images/20210615/827c2a2076fd4b2dac17343cbc7e9c17.png [2789632-3b18269684ea9294.png]: /images/20210615/21fd1b8c5bd24c3bb65d3d6a2c8bcba1.png
还没有评论,来说两句吧...