【linQ】DataContext 入门 , 和 hql , jpql 一样好用

2023-07-29,,

DataContext 和 LINQ结合后会有巨大的能量

public class UserDataContext : DataContext
{
public Table<User> Users; public UserDataContext()
: base(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\CsharpWorkspace\EntityProject\EntityProject\projectDatabase.mdf;Integrated Security=True")
{ }
} public class EfExample
{ public void SelectRecord()
{ UserDataContext ctx = new UserDataContext(); ctx.DatabaseExists(); var list = from c in ctx.Users select c;
Console.WriteLine(list.Count()); } }
using (var writer = new StreamWriter(@"E:\projects.2010\Test\LINQ2SQL_2\linq.sql", false, Encoding.UTF8))
{
//最简单的select
using (DbAppDataContext db = new DbAppDataContext())
{
//设置Log打印到的地方
db.Log = writer;
var query = from s in db.Students
select s; //返回Student表中的记录数
var cn = query.Count();
}
} 上面query.Count()执行的SQL如下: SELECT COUNT(*) AS [value]
FROM [dbo].[Student] AS [t0]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319. //更多实例 http://www.cnblogs.com/yukaizhao/archive/2010/05/14/linq_to_sql_select_2.html

感觉是不是很简洁,其实现在

ASP.NET ENTITY

也提供类似的访问方式;

另外DataContext还提供很多功能,比如日志功能,通过日志我们可以看到LINQ是如何转化为标准SQL的;例如:

ctx.log = new StreamWriter("日志文件"):

在补充一个功能,

肯能对写单元测试有用,

就是DataContext提供了Create table 和Delete Table 的能力,所以在单元测试的TestBase里能很有用,(以前用castle 的时候,也是利用castLe类似的功能来初始化数据库)

除此以外DataContext还提供了与ADO.NET的接口,可以方便使用传统ado.net的数据访问方式访问关系数据库;

(类似的做法castle ,nhernate 也有)这两种ORM工具还支持HQL和SQL的访问方式;

常用查询:

LINQ:

from c in ctx.Customers select c

HQL:

from Customers c

比较一下,区别还是有的;注意

HQL中Customers 是个领域模型

LINQ中的ctx是DataContext实例;

既然他们都是对象化的查询,那下面的例子:

LINQ:

from c in ctx.Customers  where c.ContractorName == ”tom“

select new {obj = c.ContractorName}

HQL:

from Customers c where c.ContractorName = ?// "?"表示传入的参数

上面的两个例子中的c都可以看成一个对象,

在如:

LINQ:  from c in ctx.Customers          where c.Orders.Count > 0 select c

//Customers 和Orders 是主外键关系

HQL:

from Orders o where o. Customers.ContractorName = ?

//o表示Orders这个对象,它的属性Customers也是一个对象

select Customers from Orders o where o. Customers.ContractorName = ?

//

在HQL中可以通过select 返回其他对象

使用排序:

LINQ:  from c in ctx.Employees  where c.Employees.Count >0 orderby c.EmployeeID descending , c.ReportsTo ascending   select c

注意,因为Employees 有个自链接,[ReportsTo] REFERENCES [EmployeeID],所以有c.Employees.Count >0 这个;

HQL:

from Customers c order by c.EmployeeID desc, c.ReportsTo asc

这里HQL的排序方式和T-SQL一样;

使用分组:

简单分组:

LINQ:

from c in ctx.Employees group c by c.ReportsTo select c

HQL:

from Employees e group by e.EmployeeID

带条件的分组:

LINQ:

from c in ctx.Employees       group c by c.ReportsTo into tmp        where tmp.Count() > 0  select new { 分组数= tmp.Count()}

HQL:

select count(e) from Employees e  group by e.EmployeeID   having  e.EmployeeID = 11

【linQ】DataContext 入门 , 和 hql , jpql 一样好用的相关教程结束。

《【linQ】DataContext 入门 , 和 hql , jpql 一样好用.doc》

下载本文的Word格式文档,以方便收藏与打印。