生成模型
EF有两种查询方式,Linq查询 、Lambda表达式
//普通查询 Linq 方式
IQueryable<Book> list = from b in db.Set<Book>()
where b.BookId > 5 && b.TypeId == 3
select b;
//普通查询 Lambda 方式
IQueryable<Book> list1 = db.Set<Book>()
.Where(b => b.BookId > 5 && b.TypeId == 3);
联结查询(Join)
//多表查询 Linq
var list = from book in db.Set<Book>()
join bookType in db.Set<BookType>()
on book.TypeId equals bookType.TypeId
select new
{
book
};
//多表查询 lambda
var list = db.Set<Book>()
.Where(u => u.BookId > 2 && u.TypeId == 4)
.Join(db.Set<BookType>(), book => book.TypeId, tp => tp.TypeId, (book, tp) => new { book, tp });
分页查询
//延迟加载 使用时才查询数据库 没用一次就查一次
IQueryable<Book> list = db.Set<Book>()
.OrderByDescending(u => u.BookId) //IQueryable对象中Expression方法默认将Lambda表达式转换成Expression对象
.Skip(2)
.Take(3);
//不具备延迟加载,因为IEnumerable没有方法去拼接完整sql语句
IEnumerable<Book> list1 = db.Set<Book>()
.AsEnumerable() //把结果强转成 IEnumerable 类型
.OrderByDescending(u => u.BookId)
.Skip(2)
.Take(3);
分组查询(Group)
联结两张表 然后根据 TypeName 进行分组,统计各分组下对应的数量
#原生sql
select b.TypeName,count(*) as total from TestDB.dbo.Book as a left join TestDB.dbo.BookType as b on a.TypeId = b.TypeId group by b.TypeName
//对应 lambda 表达式
public IQueryable<object> getBookTypeWithQuantity()
{
IQueryable<object> list = this.db.Set<Book>().Join(db.Set<BookType>(), b => b.TypeId, tp => tp.TypeId, (b, tp) => new { b, tp })
.GroupBy(a => new { a.tp.TypeName })
.Select(group => new { TypeName = group.Key, Total = group.Count() });
return list;
}
上面 getBookTypeWithQuantity 方法返回一个匿名对象的集合
控制器中使用
IQueryable<dynamic> list = bll.getBookTypeWithQuantity();
foreach (var item in list)
{
//这里会报错 “object”未包含“TypeName”的定义
item.TypeName.ToString();
}
string json = JsonConvert.SerializeObject(bll.getBookTypeWithQuantity());
var list = JsonConvert.DeserializeObject<dynamic>(json);
//BookTypes视图模型 包含TypeName 和 Total 两个字段
List<BookTypes> types = new List<BookTypes>();
foreach (var item in list)
{
BookTypes obj = new BookTypes();
obj.TypeName = item.TypeName.ToString();
obj.Total = (int)item.Total;
types.Add(obj);
}
增加数据
[HttpPost]
public ActionResult Add(Book book)
{
DbContext db = new DbModel();
db.Set<Book>().Add(book);
//返回受影响行数
if(db.SaveChanges() > 0)
{
return Json(new
{
msg = "添加成功"
});
}else
{
return Json(new
{
msg = "添加失败"
});
}
}
修改数据
[HttpPost] public ActionResult Edit(Book bb) { DbContext db = new DbModel(); //将对象附加到上下文 状态设置为未更改 db.Set<Book>().Attach(bb); db.Entry(bb).State = EntityState.Modified; db.SaveChanges(); return Json(new { msg = "修改成功" }); }
删除数据
public ActionResult Delete(int id) {
DbContext db = new DbModel();
Book book = db.Set<Book>().FirstOrDefault(b => b.BookId == id);
db.Set<Book>().Remove(book);
db.SaveChanges();
return Json(new
{
msg = "删除成功"
},JsonRequestBehavior.AllowGet);
}