今天做了一次Linq的测试,代码如下:
DataClasses1DataContext db = new DataClasses1DataContext();
var a = from blog in db.Blogs
where blog.Channel == db.Channels.Single<Channel>(channel => channel.Title == "生活频道")
&& blog.BlogClass == db.BlogClasses.Single<BlogClass>(c => c.Title == "默契")
select blog;
this.Title = a.Count<Blog>().ToString();
var a = from blog in db.Blogs
where blog.Channel == db.Channels.Single<Channel>(channel => channel.Title == "生活频道")
&& blog.BlogClass == db.BlogClasses.Single<BlogClass>(c => c.Title == "默契")
select blog;
this.Title = a.Count<Blog>().ToString();
这是个较为复杂的查询,包含两个跨表联合,更重要的是,最终需要的是Count,而并不是整个Blog列表,考验的是Linq的智能程度。
用Sql profile分析,得到对应的SQL是:
exec sp_executesql N'SELECT COUNT(*) AS [value]
FROM [dbo].[Blog] AS [t0]
WHERE ([t0].[ChannelID] = ((
SELECT [t1].[ChannelID]
FROM [dbo].[Channel] AS [t1]
WHERE [t1].[Title] = @p0
))) AND ([t0].[BlogClassID] = ((
SELECT [t2].[BlogClassID]
FROM [dbo].[BlogClass] AS [t2]
WHERE [t2].[Title] = @p1
)))', N'@p0 nvarchar(4),@p1 nvarchar(2)', @p0 = N'生活频道', @p1 = N'默契'
FROM [dbo].[Blog] AS [t0]
WHERE ([t0].[ChannelID] = ((
SELECT [t1].[ChannelID]
FROM [dbo].[Channel] AS [t1]
WHERE [t1].[Title] = @p0
))) AND ([t0].[BlogClassID] = ((
SELECT [t2].[BlogClassID]
FROM [dbo].[BlogClass] AS [t2]
WHERE [t2].[Title] = @p1
)))', N'@p0 nvarchar(4),@p1 nvarchar(2)', @p0 = N'生活频道', @p1 = N'默契'
从上面的SQL可以看出,Linq对代码的分析相当到位,最终着眼于Count,这应该也是得益于Lazy Load。而多表联合查询(对于Channel表和BlogClass表)也做得相当好。从这一个查询应该可以说:Linq的智能度已经相当高了,Linq已经远远超出了傻乎乎拼SQL的水平,值得一试!
鸡蛋里面挑骨头的是,BlogClass 其实和Channel有外键联系的,其实有了BlogClass的限制,Channel就可以不需要了,这是代码中故意加入的一个小Bug,可惜Linq没有自动处理这个Bug的能力,还是进行了两次查询,是不是期望太高了?呵呵。