如何将以下SQL转换为Linq?

时间:2011-08-19 16:42:39

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

我正在使用IQueryable<T>界面。

如何将以下sql语句翻译为IQueryable

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

5 个答案:

答案 0 :(得分:3)

这样的事情:

    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找到它。

答案 1 :(得分:1)

var query = 
from i in db.customer
where i.joindate > DateTime.Now 
&& (i.customertype == 'system' || i.customerstatus == 'active')
&& i.customerlocation == 'europe'
select i;

答案 2 :(得分:0)

var now = DateTime.Now;
var queryable = Customers.Where(x=>x.joindate > now && (x.customertype == "system" || x.customerstatus == "active") && x.customerlocation == "europe")

我不记得linq是否会评估DateTime.Now所以我只是提前把它扔进一个变量。

答案 3 :(得分:0)

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

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;  

答案 4 :(得分:0)

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