这部分基本都是代码,延续了初步认识EF中code first的代码。
新增数据
using (UserContext db = new UserContext())
{
var userId= db.Users.Where(a => a.UserName == "Curry").FirstOrDefault().ID;
var roleId = db.Roles.Where(a => a.RoleName == "Admin").FirstOrDefault().ID;
UserRole ur = new UserRole();
ur.UserID = userId;
ur.RoleID = roleId;
db.UserRoles.Add(ur);
db.SaveChanges();
}
这边先查询出用户名为Curry的ID,角色为Admin的ID,将两者关联
读取数据
这部分已经介绍过
using (UserContext db = new UserContext())
{
var user = from i in db.Users
where i.UserName == "Curry"
select i;
var curry = user.FirstOrDefault();
Console.WriteLine("{0}的密码是{1}", curry.UserName, curry.Password);
}
复杂的关联查询
using (UserContext db = new UserContext())
{
var user = (from i in db.Users
join o in db.UserRoles on i.ID equals o.UserID
join p in db.Roles on o.RoleID equals p.ID
where i.UserName == "Curry"
select new
{
name=i.UserName,
role=p.RoleName
}).FirstOrDefault();
Console.WriteLine("{0}的角色是{1}", user.name, user.role);
}
修改数据
using (UserContext db = new UserContext())
{
var user = db.Users.FirstOrDefault(a => a.UserName == "Curry");
user.Password = "123asd";
db.SaveChanges();
}
删除数据
using (UserContext db = new UserContext())
{
var user = db.Users.FirstOrDefault(a => a.UserName == "Jack");
db.Users.Remove(user);
db.SaveChanges();
}
事务
EF中使用事务有两种方法.BeginTransaction()和TransactionScope类
using (UserContext db = new UserContext())
{
var tran = db.Database.BeginTransaction();
try
{
var user = db.Users.FirstOrDefault(a => a.UserName == "Jack");
db.Users.Remove(user);
db.SaveChanges();
tran.Commit();//提交事务
}
catch (Exception ex)
{
tran.Rollback();//回滚
throw new Exception(ex.ToString());
}
}
使用TransactionScope类首先要引用System.Transactions.dll
using (TransactionScope scope = new TransactionScope())
{
//具体代码内容
scope.Complete();
}
//程序走出了using代码块如果还没调用Complete(),那么就会启动回滚
网友评论