Convert SQL Query to LINQ-to-SQL

2019-08-25 16:01发布

I need help converting SQL query to LINQ to 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())

How can I do that in LINQ to SQL. Thanks

3条回答
We Are One
2楼-- · 2019-08-25 16:51

try this code

( 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();
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-25 16:57

you should use this way to remove Boolean condition and reduce code

if you need to check bool condition in Ef

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

just for suggestion

查看更多
Emotional °昔
4楼-- · 2019-08-25 16:59

This was solved. Thanks to 'CodeNotFound' for this answer 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();
查看更多
登录 后发表回答