2017-05-08 148 views
0

我需要帮助的SQL查询转换为LINQ to SQL的转换SQL查询到LINQ到SQL

select top 5 customer_id, customer_name, product_id 
from Customer 
Join Product on product_id = product_id 
where (customer_active = 'TRUE') 
order by checksum(newid()) 

我怎样才能做到这在LINQ to SQL。谢谢

+1

这是一个可爱的有点不可思议,因为=>'的product_id = product_id'将alwyas返回true。你确定你的SQL有效吗?无论如何,我们可以拥有实体类和DbContext吗? – CodeNotFound

+0

是的,这只是一个示例数据,SQL正如您所建议的那样正常工作。谢谢 –

+0

@CodeNotFound:请查看下面,这是我在我的代码中做的(这只是一个例子)。如果你想要我标记这个被接受的答案,请添加你的,我会标记它。谢谢 –

回答

1

这已解决。由于“CodeNotFound”对于这个答案 https://stackoverflow.com/a/43850748/1655774

db.Customer.Where(p => p.customer_active == true).Select(p => new CustomerViewModel 
    { 
     Customer_id= p.customer_id, 
     Customer_name = p.customer_name, 
     Product_id = p.Product.product_id 
    }).OrderBy(c => SqlFunctions.Checksum(Guid.NewGuid())).Take(5).ToList(); 
0

试试这个代码

(from p in Customer 
     join q in Product on p.product_id equals q.product_id 
     join q in Product on p.product_id equals q.product_id 
     where customer_active ==true select new 
     { 
      customer_id=p.customer_id, 
      customer_name=p.customer_name, 
      product_id=q.product_id 
     }).OrderBy(c => SqlFunctions.Checksum(Guid.NewGuid())).Take(5).ToList(); 
0

,如果你需要检查布尔条件,你应该用这种方式来去除布尔条件和减少代码

Ef

1.For True Condition db.Customer.Where(p => p.customer_active).select(m => m).tolist(); 1. For False db.Customer.Where(p =>!p.customer_active).select(m => m).tolist();

只是建议