【问题标题】:linq to entities orderbylinq 到实体 orderby
【发布时间】:2011-05-24 06:59:23
【问题描述】:

如何将此查询转换为具有实体框架的实体的 linq:

SELECT  customer_id,
    customer_name,
    customer_code
FROM dbo.V_STF_CUSTOMER
WHERE   company_id=@company_id AND
ORDER BY    CASE
            WHEN ISNUMERIC(customer_name)=1 THEN 1
            ELSE 0
        END,
        customer_name

我有这个:

return CUstomers.GetQuery().
            Where(x => x.CompanyId == companyId).
        OrderBy(??This is my problem??);

我不知道如何翻译 orderby。有什么想法吗?

【问题讨论】:

标签: c# .net entity-framework linq-to-entities


【解决方案1】:
return Customers.GetQuery().
            Where(x => x.CompanyId == companyId).
        OrderBy(x=> SqlFunctions.IsNumeric(x.customer_name)).
        ThenBy(x=> x.customer_name);

【讨论】:

  • @Oskar:我认为我们需要将 Where() 之后的结果转换为 Enumerable?那么只有 Linq->EF 才能使用 IsNumeric 方法!如果我没记错的话,它应该给出一个错误提示,IsNumeric is not supported/translateable with Linq->Entities?
  • @System.ChaosException 你是什么意思? “Where”返回一个可枚举的
  • @Oskar:我的印象是Customers.GetQuery().Where() 会返回一个 IQueryable!有错请指正!
  • @System.ChaosException 可以,但是 IQueryable 实现了 IEnumrable
  • @Oskar: where 返回 IQueryable 并且它确实实现了 IEnumerable ,但不计算结果。它们在执行 select 或asenumerable 之后传递到服务器,因此实际上您编写的命令是在 .net 上而不是在 sql server 上生成的。
【解决方案2】:

您可以在查询中使用 SqlFunctions.IsNumeric 来映射到 Sql Server 中的 IsNumeric。

类似的东西:

        var results = from c in customers
                      where c.companyId = companyId
                      orderby SqlFunctions.IsNumeric(c.customerName) == 1 ? 1 : 0, c.customerName
                      select new { c.customerId, c.customerName, c.customerCode };

【讨论】:

  • 谢谢,使用名称作为第二个排序选项的排序呢?
【解决方案3】:

首先我觉得里面的SQL查询有问题

WHERE   company_id=@company_id AND

为什么要添加AND

您可以使用SqlFunctions.IsNumeric 仅在实体框架中实现 ISNUMERIC(不是 linq to sql)

return CUstomers.GetQuery().
            Where(x => x.CompanyId == companyId).
            OrderBy(x => SqlFunctions.IsNumeric(x.customer_name)).
            ThenBy(x => x.customer_name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多