【问题标题】:Convert SQL Query to LINQ-to-SQL将 SQL 查询转换为 LINQ-to-SQL
【发布时间】:2017-10-06 17:30:00
【问题描述】:

我需要帮助将 SQL 查询转换为 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())

如何在 LINQ to SQL 中做到这一点。谢谢

【问题讨论】:

  • 这有点奇怪,因为 => product_id = product_id 总是会返回 true。你确定你的 SQL 工作正常吗?无论如何,我们可以拥有实体类和您的 DbContext 吗?
  • 是的,这只是一个示例数据,SQL 可以按照您的建议正常工作。谢谢
  • @CodeNotFound:请在下面查看,这就是我在代码中所做的(这只是一个示例)。如果您希望我标记此已接受的答案,请添加您的,我会标记它。谢谢
  • 很高兴您找到了解决方案。不客气。谢谢。只要接受你自己的答案;-)

标签: sql sql-server linq linq-to-sql linq-to-entities


【解决方案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();

【讨论】:

    【解决方案2】:

    试试这个代码

    ( 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】:

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

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

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

      仅供参考

      【讨论】:

        猜你喜欢
        • 2020-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        相关资源
        最近更新 更多