EF入门-CRUD操作
一、EF数据查询
假设我们已经定义好了context:
private AccountContext db = new AccountContext();
1、[基本查询] 查询所有
var users = from u in db.SysUsers
select u;
users = db.SysUsers;
2、[条件查询] 加入查询条件
users = from u in db.SysUsers
where u.UserName == "Tom"
select u;
users = db.SysUsers.Where(u => u.UserName == "Tom");
3、[排序和分页查询]
users = (from u in db.SysUsers
orderby u.UserName
select u).Skip(0).Take(5);
users = db.SysUsers.OrderBy(u => u.UserName).Skip(0).Take(5);
NOTE:只有排序了才能分页
4、[聚合查询]
//查user总数
var num = db.SysUsers.Count();
//查最小ID
minId = db.SysUsers.Min(u => u.ID);
NOTE:聚合查询只能通过函数式查询
5、[连接查询]
var users = from ur in db. SysUserRoles
join u in db. SysUsers
on ur.SysUserID equals u.ID
select ur
二、EF数据更新
数据更新,分三步:找到对象--> 更新对象数据--> 保存更改
public ActionResult EFUpdateDemo()
{
//1.找到对象
var sysUser = db.SysUsers.FirstOrDefault(u => u.UserName == "Tom");
//2.更新对象数据
if (sysUser != null)
{
sysUser.UserName = "Tom2";
}
//3.保存修改
db.SaveChanges();
return View();
}
三、EF数据添加/删除
与UPDATE类似。
public ActionResult EFAddOrDeleteDemo()
{
//添加
//1.创建新的实体
var newSysUser = new SysUser()
{
UserName = "Scott",
Password = "tiger",
Email = "Scott@sohu.com"
};
//2.增加
db.SysUsers.Add(newSysUser);
//3.保存修改
db.SaveChanges();
//删除
//1.找到需要删除的对象
var delSysUser = db.SysUsers.FirstOrDefault(u => u.UserName == "Scott");
//2.删除
if (delSysUser!=null)
{
db.SysUsers.Remove(delSysUser);
}
//3.保存修改
db.SaveChanges();
return View("EFQueryDemo");
}