EF 拉姆达(EF Lambda)通常指的是在 Entity Framework (EF) 中使用 Lambda 表达式进行查询操作。Entity Framework 是 .NET 平台上的一个对象关系映射(ORM)框架,它允许开发者使用面向对象的方式来操作数据库。
在 Entity Framework 中,Lambda 表达式常用于 LINQ 查询中,用于定义查询条件、排序、投影等操作。Lambda 表达式使得代码更加简洁和易读。
以下是一些常见的 EF 拉姆达表达式的使用示例:
1. 基本查询
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.Where(p => p.Price > 100)
.ToList();
}
在这个例子中,Where(p => p.Price > 100)
使用了 Lambda 表达式来筛选出价格大于 100 的产品。
2. 排序
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.OrderBy(p => p.Name)
.ToList();
}
这里使用 OrderBy(p => p.Name)
对产品按名称进行升序排序。
3. 投影
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.Select(p => new { p.Name, p.Price })
.ToList();
}
在这个例子中,Select(p => new { p.Name, p.Price })
使用 Lambda 表达式来选择产品的名称和价格,并返回一个匿名类型的列表。
4. 多条件查询
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.Where(p => p.Price > 100 && p.Category == "Electronics")
.ToList();
}
这里使用了多个条件来筛选产品,p.Price > 100 && p.Category == "Electronics"
。
5. 连接查询
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.Join(context.Categories,
p => p.CategoryId,
c => c.Id,
(p, c) => new { ProductName = p.Name, CategoryName = c.Name })
.ToList();
}
在这个例子中,Join
方法使用了 Lambda 表达式来连接 Products
和 Categories
表,并返回产品名称和类别名称的组合。
6. 分组
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Products
.GroupBy(p => p.Category)
.Select(g => new { Category = g.Key, Count = g.Count() })
.ToList();
}
这里使用 GroupBy(p => p.Category)
对产品按类别进行分组,并返回每个类别的产品数量。
7. 聚合函数
csharp
复制
using (var context = new MyDbContext())
{
var totalPrice = context.Products
.Sum(p => p.Price);
}
在这个例子中,Sum(p => p.Price)
使用 Lambda 表达式来计算所有产品的总价格。
8. 嵌套查询
csharp
复制
using (var context = new MyDbContext())
{
var result = context.Categories
.Select(c => new
{
CategoryName = c.Name,
Products = c.Products.Where(p => p.Price > 100).ToList()
})
.ToList();
}
这里使用了嵌套查询,c.Products.Where(p => p.Price > 100).ToList()
在每个类别中筛选出价格大于 100 的产品。
9. 分页查询
csharp
复制
using (var context = new MyDbContext())
{
var pageSize = 10;
var pageNumber = 2;
var result = context.Products
.OrderBy(p => p.Name)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
}
在这个例子中,Skip
和 Take
方法结合 Lambda 表达式实现了分页查询。
10. 异步查询
csharp
复制
using (var context = new MyDbContext())
{
var result = await context.Products
.Where(p => p.Price > 100)
.ToListAsync();
}
这里使用了 ToListAsync()
方法进行异步查询,避免阻塞主线程。
总结
EF 拉姆达表达式在 Entity Framework 中非常强大,能够简化数据库操作,并且使代码更加易读和易维护。通过结合 LINQ,开发者可以轻松地实现复杂的查询逻辑。