自定义属性和lambda表达式 [英] Custom properties and lambda expressions

查看:167
本文介绍了自定义属性和lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经向LINQ-to-SQL实体添加了一个自定义属性:

I've added a custom property to a LINQ-to-SQL entity:

public partial class User
{
    public bool IsActive
    {
        get
        {
            // note that startDate and endDate are columns of User table
            return startDate <= DateTime.Now && endDate >= DateTime.Now;
        }
    }
}

现在我需要将此属性与lambda表达式一起使用:

and now I need to use this property with lambda expressions:

activeUsers = users.Where(u => u.IsActive);

但是执行此代码时,我得到一个System.NotSupportedException.异常消息显示不支持成员'User.IsActive'的SQL转换" .

but when this code is executed I get a System.NotSupportedException. The exception message says that "SQL conversions for the member 'User.IsActive' are not supported".

有没有办法解决这个问题?

Is there a way to solve this problem?

推荐答案

您显示的IsActive是常规C#-将被编译为IL,并且不可用于LINQ-to-SQL(etc)进行检查和转换为TSQL以在数据库中执行.这里的一种选择可能是:

The IsActive you show is regular C# - it will be compiled to IL and will not be available for LINQ-to-SQL (etc) to inspect and turn into TSQL to execute at the database. One option here might be:

public static Expression<Func<User,bool>> GetIsActiveFilter() {
    return user => user.StartDate <= DateTime.Now &&
                   user.EndDate >= DateTime.Now;
}

那么您应该可以使用:

activeUsers = users.Where(User.GetIsActiveFilter());

或者类似地-也许是一种扩展方法:

Or similarly - maybe an extension method:

public static IQueryable<User> ActiveOnly(this IQueryable<User> users) {
    return users.Where(user => user.StartDate <= DateTime.Now &&
                               user.EndDate >= DateTime.Now);
}

然后:

activeUsers = users.ActiveOnly();

这里的区别是,我们始终使用IQueryable<T>接口和表达式树,这使LINQ能够理解我们的意图,并创建合适的TSQL来实现一样.

The difference here is that we are using the IQueryable<T> interface and expression trees throughout, which allows LINQ to understand our intent, and create suitable TSQL to achieve the same.

这篇关于自定义属性和lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆