【问题标题】:How to execute code as a part of the LINQ query如何在 LINQ 查询中执行代码
【发布时间】:2010-09-01 13:56:55
【问题描述】:

我的查询如下所示:

    var results = from person
                  where <here I need to do something like if person is of type 
Employee, call person.GetSalary() > 100000 but if the person is of type Contractor, I need to execute 
several lines of code before doing a person.GetSalary() > 100000 
                  select new {person.Name}

难点在于构造 where 子句。有人可以帮我完成这个查询吗?

【问题讨论】:

    标签: .net asp.net-mvc linq linq-to-entities


    【解决方案1】:

    您始终可以编写一个执行逻辑检查的方法,并在单独的 where 子句中调用它。要使用 LINQ-to-Entities 执行此操作,您必须首先使用 AsEnumerable() 实现结果:

    bool CheckEmployeeOrContractorSalary( Person p, decimal salaryLevel )
    {
       // put your employee and contractor logic here...
       if( p is Employee ) {
           return p.GetSalary() > salaryLevel; }
       else if( p is Contractor ) {
           // ... your complex logic...
           return p.GetSalary() > salaryLevel; }
       else
           // ??? 
           return false;
    }
    

    现在你可以写了:

    var results = from person in (
                      (from p in person select new { p.Name } ).AsEnumerable())
                  where CheckEmployeeOrContractorSalary( person, 100000 )
                  select new {person.Name};
    

    【讨论】:

    • 问题被标记为“Linq to Entities”;自定义方法不能转换为 SQL,因此如果这样做,您需要在本地过滤结果(通过在 Where 之前调用 AsEnumerable)
    • @Thomas - 你能详细说明为什么这个解决方案不起作用,是的,它是 Linq to Entities。
    • 我的另一个问题是 - 如何调试 linq 查询?假设我有一个非常长的 linq 查询,其中包含一堆 where、join 和 let,我需要将断点放在其中一行上以检查值。看来这是不可能的。
    • @DotnetDude,Linq to Entities 查询被转换为 SQL 并在数据库上执行。因此,您只能使用查询生成器识别的构造和方法,CheckEmployeeOrContractorSalary 方法当然不是这种情况。关于调试,您不能在 Linq 查询中放置断点,因为正如我所说,它不是在本地执行而是在数据库上执行
    • @Thomas Levesque: 你是对的。我错过了那个标签。我会编辑我的回复。 @DotnetDude: 调试 LINQ 可能有点棘手。您仍然可以在 LINQ-to-objects 查询中的任何方法或表达式中设置断点,但要意识到只有在开始枚举结果时才会遇到这些断点。在 LINQ 查询中调试诸如连接和选择之类的东西实际上是不可能的——因为实现隐藏在 Enumerable 类的行为中。如果可能,一种方法是从有效的简单查询构建复杂查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多