基础查询
Mego 使用语言集成查询(LINQ)从数据库查询数据。LINQ允许您使用C#(或其他.NET语言)根据派生的上下文和实体类编写强类型查询。将LINQ查询的表示传递给数据库提供者,翻译为数据库特定的查询语言(例如关系数据库的SQL)。
文档代码示例的模型都是基于测试用例所用的模型。
加载所有数据
using (var db = new OrderManageEntitie())
{
var list = db.Products.ToList();
}
加载单个数据
比较常用的方法,可以支持First()
、Single()
、ElementAt()
。
using (var db = new OrderManageEntit())
{
var data = db.Products.FirstOrDefault();
}
using (var db = new OrderManageEntit())
{
var data = db.Products.ElementAt(4);
}
汇总查询
using (var db = new OrderManageEntit())
{
var data = db.Products.Count();
}
查询过滤
using (var db = new OrderManageEnti())
{
var data = db.Products.Where(a => a.Name.Contains("P")).ToArray();
}
查询投影
using (var db = new OrderManageEntiti())
{
var query = from a in db.Products
select new
{
a.Id,
a.Name
};
var data = query.ToList();
}
查询分页
using (var db = new OrderManageEntities())
{
var data = db.Products.Take(10).Skip(20);
}
内连接查询
using (var db = new OrderManageEntities())
{
var query = from a in db.Products
join b in db.Customers on a.Id equals b.Id
select new { a, b };
var data = query.ToList();
}
左连接查询
using (var db = new OrderManageEntities())
{
var query = from a in db.Products
join b in db.Customers on a.Id equals b.Id into g
from b in g.DefaultIfEmpty()
select new { a, b };
var data = query.ToList();
}
多查询连接
using (var db = new OrderManageEntities())
{
var query = (from a in db.Customers
select new
{
a.Id,
a.Code,
a.Name
})
.Concat
(from b in db.Products
select new
{
b.Id,
b.Code,
b.Name
});
var data = query.ToArray();
}