将 SQL 查询转换为 LINQ-to-SQL

Convert SQL Query to 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 中做到这一点?谢谢

已解决。感谢 'CodeNotFound' 的回答

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();

试试这个代码

( 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();

您应该使用这种方法来删除布尔条件并减少代码

如果您需要检查 Ef 中的 bool 条件

1.For 真实情况 db.Customer.Where(p => p.customer_active).select(m=>m).tolist(); 1.For 错误条件 db.Customer.Where(p => !p.customer_active).select(m=>m).tolist();

仅供参考