Entity Framework 第四篇 优化SQL查询

Expression<Func<TEntity, bool>>与Func<TEntity, bool>的异同
  public IList<TEntity> Search<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class
        {
            if (predicate == null)
            {
                return dbContext.Set<TEntity>().ToList();
            }
            else
            {
                return dbContext.Set<TEntity>().Where(predicate).ToList();
            }

        }

本人通过跟踪sql语句得知

predicate如果为委托类型的时候,dbContext.Set<TEntity>().Where(predicate).ToList();对应的sql语句是

SELECT 
    [Extent1].[UserID] AS [UserID], 
    [Extent1].[LoginName] AS [LoginName], 
    [Extent1].[Password] AS [Password], 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[UserType] AS [UserType], 
    [Extent1].[Tel] AS [Tel], 
    [Extent1].[CreateDate] AS [CreateDate], 
    [Extent1].[LoginNum] AS [LoginNum], 
    [Extent1].[LastDate] AS [LastDate], 
    [Extent1].[ShopID] AS [ShopID]
    FROM [dbo].[S_Users] AS [Extent1]
   

但是当predicate如果为表达式树的时候,语句如下,

SELECT 
    [Extent1].[UserID] AS [UserID], 
    [Extent1].[LoginName] AS [LoginName], 
    [Extent1].[Password] AS [Password], 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[UserType] AS [UserType], 
    [Extent1].[Tel] AS [Tel], 
    [Extent1].[CreateDate] AS [CreateDate], 
    [Extent1].[LoginNum] AS [LoginNum], 
    [Extent1].[LastDate] AS [LastDate], 
    [Extent1].[ShopID] AS [ShopID]
    FROM [dbo].[S_Users] AS [Extent1]
    WHERE N'liuyangh' = [Extent1].[LoginName]

所以我们尽量用表达式树传参,而不是单纯地lambda表达式或者委托类型。

为什么会这样呢?

因为dbContext.Set<TEntity>().Where(predicate),当是表达式树的时候返回的是IQueryable<TSource>

public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);

  如果是委托类型返回的是IEnumerable<TSource>
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

 

转载于:https://www.cnblogs.com/njcxwz/p/5581388.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值