【问题标题】:How to translate the following SQL to Linq?如何将以下 SQL 翻译成 Linq?
【发布时间】:2011-08-19 16:42:39
【问题描述】:

我正在使用IQueryable<T> 接口。

如何将下面的sql语句翻译成IQueryable

select * from customer
where joindate > DateTime.Now and
      (customertype = 'system' or customerstatus = 'active') and
      customerlocation = 'europe'

【问题讨论】:

    标签: c# linq linq-to-sql iqueryable


    【解决方案1】:

    类似这样的:

        var result = from record in context.customer 
        where record.joindate > DateTime.Now && 
            (record.customertype == "system" || record.customerstatus == "active") && 
            record.customerlocation == "europe"
        select record
    

    有一个不错的工具,Linqer,它可以帮助您将 SQL 查询转换为 LINQ。当然,对于这种简单的情况,它是矫枉过正的,但如果你对 SQL 更熟悉的话,当然可以考虑使用它来处理繁重的查询。

    你可以在这里找到它LINQER

    【讨论】:

      【解决方案2】:
      var query = 
      from i in db.customer
      where i.joindate > DateTime.Now 
      && (i.customertype == 'system' || i.customerstatus == 'active')
      && i.customerlocation == 'europe'
      select i;
      

      【讨论】:

        【解决方案3】:
        var now = DateTime.Now;
        var queryable = Customers.Where(x=>x.joindate > now && (x.customertype == "system" || x.customerstatus == "active") && x.customerlocation == "europe")
        

        我不记得 linq 是否会评估 DateTime.Now,所以我只是提前将它放入变量中。

        【讨论】:

          【解决方案4】:

          我更喜欢以下语法,但您也可以使用查询语法:

          var results = yourContext.Customers.Where(c => (c.JoinDate > DateTime.Now) &&
              ((c.CustomerType.Equals("system") || (c.CustomerType.Equals("active")) &&
              (c.CustomerLocation.Equals("europe")));
          

          使用查询语法:

          var results = from c in yourContext.Customers
              where (c.JoinDate > DateTime.Now) &&
              (c.CustomerType.Equals("system") || c.CustomerStatus.Equals("active")) &&
              c.CustomerLocation.Equals("europe")
              select c;  
          

          【讨论】:

            【解决方案5】:
            var result = (from c in customer
                          where (c.joindate > DateTime.Now) &&
                                (c.customertype == "system" || c.customerstatus == "active") &&
                                (c.customerlocation == "europe")
                          select c)
                         .ToList();
            

            【讨论】:

            • 你没有把 customerlocation == 'europe'
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多