Entity Framework框架 (一)

1. Entity Framework的详细介绍:

Entity Framework简称EF,与Asp.net关系与Ado.net关系。

Entity Framework是ado.net中的一组支持开发面向数据的软件应用程序的技术,是微软的一个ORM框架。

ORM:object relation mapping 是基于关系型数据库的数据储备,实现一个模拟的面向对象的数据访问接口,理想情况下,基于这样一个面向对象的接口,持久化一个oo对象应该不需要了解任何关系型数据库存储数据的实现细节。

类似的轻量级的orm框架,dapper,patapoct

 1. lambda表达式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    //定义一个委托
    public delegate int AddSum(int a,int b);
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
           // AddSum addSum = new AddSum(p.Add);
           // AddSum addSum = delegate(int a, int b) { return a + b; };
            //AddSum addSum = (int a, int b) => { return a + b; };
            //简化之后的lambda表达式
            AddSum addSum = ( a,  b) => { return a + b; };
            int sum = addSum(5, 3);
            Console.WriteLine(sum);
            Console.ReadKey();
        }

        //public int Add(int a, int b)
        //{
        //    return a + b;
        //}
    }
    
}
lambda表达式

一、第一种使用EF的方法:先有数据库再建立数据模型

 1. 在项目中右击新建,新建一个ADO.net实体数据模型,选择从数据库生成,这种是先有数据库再建立数据模型的方式。然后依次点击下一步便可,完成以后切记点击ctrl+s保存。不然是不会生成数据模型对应的类。

 2. 注意:对应的数据库表必须有主键,不然在使用时会报错。

 3. 生成之后的结构如下。 

 4.使用EF进行相关的增删改查代码如下:

 新建的web窗体页面,分别放四个button按钮便可。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 
  8 namespace WebApplication2
  9 {
 10     public partial class WebForm1 : System.Web.UI.Page
 11     {
 12         protected void Page_Load(object sender, EventArgs e)
 13         {
 14 
 15         }
 16         /// <summary>
 17         /// 插入数据
 18         /// </summary>
 19         /// <param name="sender"></param>
 20         /// <param name="e"></param>
 21         protected void Button1_Click(object sender, EventArgs e)
 22         {
 23             UserInfo UserInfo = new UserInfo();
 24             UserInfo.UserName = "张五呀";
 25             UserInfo.UserPass = "123qwe";
 26             UserInfo.RegTime = 2;
 27             UserInfo.Email = "wangjin";
 28             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 29             //将数据添加到EF中,并且添加了标记,并且类似于生成了一条insert语句,但是这时候还没有执行该语句
 30             db.UserInfo.Add(UserInfo);
 31             //之后执行该代码时,才会执行insert语句,并且返回受影响行数
 32             db.SaveChanges();
 33             //返回刚刚插入的主键ID
 34             Response.Write(UserInfo.ID);
 35         }
 36         /// <summary>
 37         /// 查询数据
 38         /// </summary>
 39         /// <param name="sender"></param>
 40         /// <param name="e"></param>
 41         protected void Button2_Click(object sender, EventArgs e)
 42         {
 43             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 44             var userinfolist = from u in db.UserInfo   //linq表达式
 45                                where u.ID == 65 
 46                                select u;
 47             //EF的延迟加载机制,只有数据在使用的时候才会去数据库中查询,不用的时候不查询。
 48             //只有执行下面的代码的时候才会去执行,这样可以提高整体的性能
 49             foreach (var userinfo in userinfolist)
 50             {
 51                 Response.Write(userinfo.ID);
 52             }
 53             //FirstOrDefault  查询第一条数据或者查询默认值
 54             //userinfolist.FirstOrDefault();
 55         }
 56         /// <summary>
 57         /// 删除数据
 58         /// </summary>
 59         /// <param name="sender"></param>
 60         /// <param name="e"></param>
 61         protected void Button3_Click(object sender, EventArgs e)
 62         {
 63             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 64             var userinfolist = from u in db.UserInfo
 65                                where u.ID == 66
 66                                select u;
 67             //返回第一条数据,如果没有就放回null
 68             UserInfo userinfo = userinfolist.FirstOrDefault();
 69             if (userinfo != null)
 70             {
 71                 db.UserInfo.Remove(userinfo);
 72                 db.SaveChanges();
 73                 Response.Write("删除成功");
 74             }
 75             else
 76             {
 77                 Response.Write("数据有误");
 78             }
 79             
 80             ////执行删除的第二种方法
 81             //UserInfo userInfo = new UserInfo() {ID=344};
 82             db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Deleted;
 83             //db.SaveChanges();
 84         }
 85 
 86         /// <summary>
 87         /// 修改数据
 88         /// </summary>
 89         /// <param name="sender"></param>
 90         /// <param name="e"></param>
 91         protected void Button4_Click(object sender, EventArgs e)
 92         {
 93             //构建一个
 94             AdwResourcesEntities1 db = new AdwResourcesEntities1();
 95             var userinfolist = from u in db.UserInfo
 96                                where u.ID == 65
 97                                select u;
 98             UserInfo userinfo = userinfolist.FirstOrDefault();
 99             userinfo.UserPass = "qweqwe";
100             db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Modified;
101             db.SaveChanges();
102             Response.Write("修改成功");
103         }
104     }
105 }

 

 二、第二种ModelFirst模式使用EF的方法,先建立数据模型,再生成数据库对应的表。

 1. 先在数据库中新建一个数据库。

 2.  在项目中右击新建项目,选择数据源,点击空模型。

 3. 在生成的空白界面中,右击新增实体,新增之后再新增标量属性,如果是多表,并且有关联的表,右击新增关联,再右击根据数据模型生成数据库。

 4. 点击如下文件,需要点击执行才会生成数据库。

 5. 使用第二种进行增删改查的相关代码如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 
  8 namespace WebApplication1
  9 {
 10     public partial class WebForm2 : System.Web.UI.Page
 11     {
 12         protected void Page_Load(object sender, EventArgs e)
 13         {
 14 
 15         }
 16         /// <summary>
 17         /// 插入数据
 18         /// </summary>
 19         /// <param name="sender"></param>
 20         /// <param name="e"></param>
 21         protected void Button1_Click(object sender, EventArgs e)
 22         {
 23             Model2Container db = new Model2Container();
 24             Customer customer = new Customer() {CustomerName="zhangsan",CustomerPwd="123", SubTime=DateTime.Now };
 25             // Customer = customer导航属性,代表下面的数据属于上面的值
 26             OrderInfo orderInfo1 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "10001", CreateDateTime = DateTime.Now,Customer=customer };
 27             OrderInfo orderInfo2 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "10002", CreateDateTime = DateTime.Now, Customer = customer };
 28             db.Customer.Add(customer);
 29             db.OrderInfo.Add(orderInfo1);
 30             db.OrderInfo.Add(orderInfo2);
 31             db.SaveChanges();//默认的已经开启了事务。 工作单元模式。(UnitOfwork)
 32         }
 33         /// <summary>
 34         /// 查询数据
 35         /// </summary>
 36         /// <param name="sender"></param>
 37         /// <param name="e"></param>
 38         protected void Button2_Click(object sender, EventArgs e)
 39         {
 40             Model2Container db = new Model2Container();
 41             var customerList = from c in db.Customer
 42                                select c;
 43             foreach (var customer in customerList)
 44             {
 45                 Response.Write(customer.CustomerName+":");
 46 
 47 
 48                 foreach (var orderInfo in customer.OrderInfo)//延迟加载。
 49                 {
 50                     Response.Write(orderInfo.OrderNum);
 51                 }
 52             }
 53         }
 54         /// <summary>
 55         /// 根据名字id查询所有的订单
 56         /// </summary>
 57         /// <param name="sender"></param>
 58         /// <param name="e"></param>
 59         protected void Button3_Click(object sender, EventArgs e)
 60         {
 61             Model2Container db = new Model2Container();
 62             //var customerInfoList = from c in db.Customer
 63             //                   where c.ID == 1
 64             //                   select c;
 65             //var customerInfo = customerInfoList.FirstOrDefault();
 66             //foreach (var orderInfo in customerInfo.OrderInfo)
 67             //{
 68             //    Response.Write(orderInfo.OrderNum);
 69             //}
 70 
 71             var orderInfoList = from o in db.OrderInfo
 72                                where o.CustomerID == 1
 73                                select o;
 74             foreach (var orderInfo in orderInfoList)
 75             {
 76                 Response.Write(orderInfo.OrderNum);
 77             }
 78                            
 79         }
 80         /// <summary>
 81         /// 输出10001对应的客户ID
 82         /// </summary>
 83         /// <param name="sender"></param>
 84         /// <param name="e"></param>
 85         protected void Button4_Click(object sender, EventArgs e)
 86         {
 87              Model2Container db = new Model2Container();
 88              var orderInfoList = from o in db.OrderInfo
 89                                  where o.OrderNum == "10001"
 90                                  select o;
 91              var orderInfo = orderInfoList.FirstOrDefault();
 92              Customer customer = orderInfo.Customer;
 93              Response.Write(customer.CustomerName);
 94         }
 95         /// <summary>
 96         /// 根据人员ID删除对应数据
 97         /// </summary>
 98         /// <param name="sender"></param>
 99         /// <param name="e"></param>
100         protected void Button5_Click(object sender, EventArgs e)
101         {
102             Model2Container db = new Model2Container();
103             //var customer = (from c in db.Customer
104             //                where c.ID == 1
105             //                select c).FirstOrDefault();
106             //var orderInfoList = customer.OrderInfo;
107             //while (orderInfoList.Count > 0)
108             //{
109             //    var orderInfo = orderInfoList.FirstOrDefault();
110             //    db.Entry<OrderInfo>(orderInfo).State = System.Data.EntityState.Deleted;
111             //}
112             //db.SaveChanges();
113 
114             var orderList = from o in db.OrderInfo
115                             where o.CustomerID == 2
116                             select o;
117 
118         }
119 
120     }
121 }

 三、第三种codeFirst模式,该模式是指不建立数据模型,并且不建立建立数据库的情况下,通过代码的形式去新建一个数据库。

   1. :创建实体类,并且给实体加上特性标签,并且标注一下实体类之间的关系。

     1.1创建classInfo(班级)实体类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace CodeFirstDemo
 9 {
10    public class ClassInfo
11     {
12        [Key]  //特性标签
13        public int Id { get; set; }
14        [StringLength(32)]   //指定是字符串类型
15        [Required]            //必填项
16        public string ClassName { get; set; }
17        [Required]
18        public DateTime CreateTime { get; set; }
19        //表示1对多,指一个班级对应多个学生
20        public virtual ICollection<StudentInfo> StudentInfo { get; set; }
21     }
22 }

  1.2 :创建学生实体类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace CodeFirstDemo
 9 {
10    public class StudentInfo
11     {
12        [Key]
13        public int Id { get; set; }
14        [StringLength(32)]
15        [Required]
16        public string StuName { get; set; }
17         [Required]
18        public DateTime SubTime { get; set; }
19        public virtual ClassInfo ClassInfo { get; set; }  //表明外键关系,多对1
20     }
21 }

1.3. 引用Entity

  方法1,点击引用,system.data.Entity

  方法2. 新建一个数据模型,之后删掉,此时已经自动引用了entity

1.4 :创建codefirstdbcontext:dbcontext文件

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Entity;
 4 using System.Data.Entity.ModelConfiguration.Conventions;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace CodeFirstDemo
10 {
11    public class CodeFirstDbContext:DbContext
12     {
13        public CodeFirstDbContext()
14            : base("name=connStr")  //对应连接数据库字符串的名字
15        {
16 
17        }
18        protected override void OnModelCreating(DbModelBuilder modelBuilder)
19        {
20            //此代码的功能是移除复数的约定  就是指生成的表名后面不加S
21            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
22        }
23         //对应的表
24        public DbSet<ClassInfo> ClassInfo { get; set; }
25        public DbSet<StudentInfo> StudentInfo { get; set; }
26     }
27 }

1.5 :在配置文件构建数据库链接字符串。

1  <configSections>
2     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
3   </configSections>

 

1.6:查询部分数据以及实例创建代码

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

namespace WebApplication1
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 只查询其中几列数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            //使用HttpContext,只要持续调用,就一直都不会中断 
            EFFristModelEntities db = null;
            if (HttpContext.Current.Items["db"] == null)
            {
                db = new EFFristModelEntities();
                HttpContext.Current.Items["db"] = db;
            }
            else
            {
                db = HttpContext.Current.Items["db"] as EFFristModelEntities;
            }

           var userInfoList = from u in db.UserInfo
                               where u.ID == 343
                               select  new{UName=u.UserName,UPwd=u.UserPass};    //新建一个匿名类查询
            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.UName+":"+userInfo.UPwd);
            }

        }
        /// <summary>
        /// 匿名函数来查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
          //  Func<UserInfo, bool> whereLambda = u => { return u.ID == 343; };
          
            EFFristModelEntities db = new EFFristModelEntities();
            //var userInfoList = db.UserInfo.Where<UserInfo>(u=>u.ID==3);
           
            //select * from UserInfo where id=343
            //升序排序
            //var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderBy<UserInfo, int>(u => u.ID);
            //降序排序
         //var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderByDescending(u => u.ID);

            int pageIndex = 2;
            int pageSize = 2;
            var userInfoList = (from u in db.UserInfo
                                where u.ID > 0
                                orderby u.RegTime ascending, u.ID descending
                                select u).Skip<UserInfo>((pageIndex - 1) * pageSize).Take<UserInfo>(pageSize);
         
      //   var userInfoList = db.UserInfo.Where<UserInfo>(U => true).OrderByDescending(u => u.UserPass).ThenByDescending<UserInfo, int>(u => u.ID);//Skip:表示跳过多少条记录, Take取多少条记录

      
            foreach (var userInfo in userInfoList)
            {
             
                    Response.Write(userInfo.UserName + "<br/>");
              
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            string str ="ttttt";
          Response.Write (str.MyStr());
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            EFFristModelEntities db = new EFFristModelEntities();
          
            var userInfoList = db.UserInfo.Where<UserInfo>(u => u.ID >0);
        
            int i = 0;
            int count = userInfoList.Count();
            Response.Write(count);

        }
    }
}
查询部分数据以及实例创建代码

以上就是EF创建和操作的详细介绍,欢迎评论和留言

 2:如果在.net core中启动ef的事务,具体如下:

     try
                {
                    using (var _activitydb = db.Database.BeginTransaction())
                    {
                        try
                        {
                            li.ForEach(o => o.IsMake = 1);
                            db.UpdateRange(li);
                            List<LogoNum> logolist = new List<LogoNum>();
                            for (int i = 0; i < isLogonum; i++)
                            {
                                LogoNum logo = new LogoNum();
                                logo.LogoNums = 1;
                                logo.UserId = userId;
                                logo.CreateTime = DateTime.UtcNow.AddHours(8);
                                logo.UserName = user.UserName;
                                logo.SiteId = siteId;
                                logolist.Add(logo);
                            }

                            db.LogoNum.AddRange(logolist);
                            int res = db.SaveChanges();
                            if (res < 1)
                            {
                                _activitydb.Rollback();
                                return -1;
                            }
                            _activitydb.Commit();
                            return isLogonum;
                        }
                        catch (Exception)
                        {
                            _activitydb.Rollback();
                            throw;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw;
                }

 

posted @ 2019-03-24 09:07  锦大大的博客呀!  阅读(17520)  评论(0编辑  收藏  举报