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(, );
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按钮便可。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace WebApplication2
{
public partial class WebForm1 : 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)
{
UserInfo UserInfo = new UserInfo();
UserInfo.UserName = "张五呀";
UserInfo.UserPass = "123qwe";
UserInfo.RegTime = ;
UserInfo.Email = "wangjin";
AdwResourcesEntities1 db = new AdwResourcesEntities1();
//将数据添加到EF中,并且添加了标记,并且类似于生成了一条insert语句,但是这时候还没有执行该语句
db.UserInfo.Add(UserInfo);
//之后执行该代码时,才会执行insert语句,并且返回受影响行数
db.SaveChanges();
//返回刚刚插入的主键ID
Response.Write(UserInfo.ID);
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
AdwResourcesEntities1 db = new AdwResourcesEntities1();
var userinfolist = from u in db.UserInfo //linq表达式
where u.ID ==
select u;
//EF的延迟加载机制,只有数据在使用的时候才会去数据库中查询,不用的时候不查询。
//只有执行下面的代码的时候才会去执行,这样可以提高整体的性能
foreach (var userinfo in userinfolist)
{
Response.Write(userinfo.ID);
}
//FirstOrDefault 查询第一条数据或者查询默认值
//userinfolist.FirstOrDefault();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button3_Click(object sender, EventArgs e)
{
AdwResourcesEntities1 db = new AdwResourcesEntities1();
var userinfolist = from u in db.UserInfo
where u.ID ==
select u;
//返回第一条数据,如果没有就放回null
UserInfo userinfo = userinfolist.FirstOrDefault();
if (userinfo != null)
{
db.UserInfo.Remove(userinfo);
db.SaveChanges();
Response.Write("删除成功");
}
else
{
Response.Write("数据有误");
} ////执行删除的第二种方法
//UserInfo userInfo = new UserInfo() {ID=344};
db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Deleted;
//db.SaveChanges();
} /// <summary>
/// 修改数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button4_Click(object sender, EventArgs e)
{
//构建一个
AdwResourcesEntities1 db = new AdwResourcesEntities1();
var userinfolist = from u in db.UserInfo
where u.ID ==
select u;
UserInfo userinfo = userinfolist.FirstOrDefault();
userinfo.UserPass = "qweqwe";
db.Entry<UserInfo>(userinfo).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
Response.Write("修改成功");
}
}
}
二、第二种ModelFirst模式使用EF的方法,先建立数据模型,再生成数据库对应的表。
1. 先在数据库中新建一个数据库。
2. 在项目中右击新建项目,选择数据源,点击空模型。
3. 在生成的空白界面中,右击新增实体,新增之后再新增标量属性,如果是多表,并且有关联的表,右击新增关联,再右击根据数据模型生成数据库。
4. 点击如下文件,需要点击执行才会生成数据库。
5. 使用第二种进行增删改查的相关代码如下:
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 WebForm2 : 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)
{
Model2Container db = new Model2Container();
Customer customer = new Customer() {CustomerName="zhangsan",CustomerPwd="", SubTime=DateTime.Now };
// Customer = customer导航属性,代表下面的数据属于上面的值
OrderInfo orderInfo1 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "", CreateDateTime = DateTime.Now,Customer=customer };
OrderInfo orderInfo2 = new OrderInfo() { ID = Guid.NewGuid(), OrderNum = "", CreateDateTime = DateTime.Now, Customer = customer };
db.Customer.Add(customer);
db.OrderInfo.Add(orderInfo1);
db.OrderInfo.Add(orderInfo2);
db.SaveChanges();//默认的已经开启了事务。 工作单元模式。(UnitOfwork)
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
Model2Container db = new Model2Container();
var customerList = from c in db.Customer
select c;
foreach (var customer in customerList)
{
Response.Write(customer.CustomerName+":"); foreach (var orderInfo in customer.OrderInfo)//延迟加载。
{
Response.Write(orderInfo.OrderNum);
}
}
}
/// <summary>
/// 根据名字id查询所有的订单
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button3_Click(object sender, EventArgs e)
{
Model2Container db = new Model2Container();
//var customerInfoList = from c in db.Customer
// where c.ID == 1
// select c;
//var customerInfo = customerInfoList.FirstOrDefault();
//foreach (var orderInfo in customerInfo.OrderInfo)
//{
// Response.Write(orderInfo.OrderNum);
//} var orderInfoList = from o in db.OrderInfo
where o.CustomerID ==
select o;
foreach (var orderInfo in orderInfoList)
{
Response.Write(orderInfo.OrderNum);
} }
/// <summary>
/// 输出10001对应的客户ID
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button4_Click(object sender, EventArgs e)
{
Model2Container db = new Model2Container();
var orderInfoList = from o in db.OrderInfo
where o.OrderNum == ""
select o;
var orderInfo = orderInfoList.FirstOrDefault();
Customer customer = orderInfo.Customer;
Response.Write(customer.CustomerName);
}
/// <summary>
/// 根据人员ID删除对应数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button5_Click(object sender, EventArgs e)
{
Model2Container db = new Model2Container();
//var customer = (from c in db.Customer
// where c.ID == 1
// select c).FirstOrDefault();
//var orderInfoList = customer.OrderInfo;
//while (orderInfoList.Count > 0)
//{
// var orderInfo = orderInfoList.FirstOrDefault();
// db.Entry<OrderInfo>(orderInfo).State = System.Data.EntityState.Deleted;
//}
//db.SaveChanges(); var orderList = from o in db.OrderInfo
where o.CustomerID ==
select o; } }
}
三、第三种codeFirst模式,该模式是指不建立数据模型,并且不建立建立数据库的情况下,通过代码的形式去新建一个数据库。
1. :创建实体类,并且给实体加上特性标签,并且标注一下实体类之间的关系。
1.1创建classInfo(班级)实体类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CodeFirstDemo
{
public class ClassInfo
{
[Key] //特性标签
public int Id { get; set; }
[StringLength()] //指定是字符串类型
[Required] //必填项
public string ClassName { get; set; }
[Required]
public DateTime CreateTime { get; set; }
//表示1对多,指一个班级对应多个学生
public virtual ICollection<StudentInfo> StudentInfo { get; set; }
}
}
1.2 :创建学生实体类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CodeFirstDemo
{
public class StudentInfo
{
[Key]
public int Id { get; set; }
[StringLength()]
[Required]
public string StuName { get; set; }
[Required]
public DateTime SubTime { get; set; }
public virtual ClassInfo ClassInfo { get; set; } //表明外键关系,多对1
}
}
1.3. 引用Entity
方法1,点击引用,system.data.Entity
方法2. 新建一个数据模型,之后删掉,此时已经自动引用了entity
1.4 :创建codefirstdbcontext:dbcontext文件
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CodeFirstDemo
{
public class CodeFirstDbContext:DbContext
{
public CodeFirstDbContext()
: base("name=connStr") //对应连接数据库字符串的名字
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//此代码的功能是移除复数的约定 就是指生成的表名后面不加S
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
//对应的表
public DbSet<ClassInfo> ClassInfo { get; set; }
public DbSet<StudentInfo> StudentInfo { get; set; }
}
}
1.5 :在配置文件构建数据库链接字符串。
<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 ==
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 = ;
int pageSize = ;
var userInfoList = (from u in db.UserInfo
where u.ID >
orderby u.RegTime ascending, u.ID descending
select u).Skip<UserInfo>((pageIndex - ) * 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 >); int i = ;
int count = userInfoList.Count();
Response.Write(count); }
}
}
查询部分数据以及实例创建代码
以上就是EF创建和操作的详细介绍,欢迎评论和留言