【问题标题】:Assistance to convert my SQL query to LINQ?协助将我的 SQL 查询转换为 LINQ?
【发布时间】:2021-02-15 21:05:10
【问题描述】:

我需要一些帮助来将此查询转换为 LINQ:

SELECT
    st.ProductId, st.ProductType, st.StockValue, st.InOut, st.SupplierCmdId, st.CreationDate,
    (SELECT su.Id FROM Suppliers AS su 
     WHERE su.Id = (SELECT suo.SupplierId FROM SupplierOrders AS suo 
                    WHERE suo.Id = st.SupplierCmdId)) AS SupplerId
FROM 
    StockDetails AS st 
WHERE 
    st.ProductType = 'Yarn' 
    AND st.ProductId = 2835 
ORDER BY 
    st.CreationDate DESC

输出:

ProductId   ProductType StockValue  InOut   SupplierCmdId   CreationDate                SupplerId
2835        Yarn        10          1       1450            2020-03-12 15:25:54.000     151
2835        Yarn        5           0       NULL            2019-03-04 00:00:00.000     NULL
2835        Yarn        5           0       NULL            2018-12-23 00:00:00.000     NULL
2835        Yarn        10          1       1398            2018-12-17 10:51:17.000     151

提前致谢

我试过了:

var ProductType = "Yarn";
var ProductId = 2835;

stocks = (from st in _context.StockDetails
join sn in _context.StockStatus on st.StatusId equals sn.Id
where st.ProductId == ProductId 
      && st.ProductType == ProductType 
orderby st.CreationDate descending
select new StockList
    {
    StockValue = st.StockValue,
    InOut = st.InOut,
    SupplierCmdId = st.SupplierCmdId,
    CreationDate = st.CreationDate
    });

在此我需要找到供应商 ID(请参阅 SQL 查询)

【问题讨论】:

  • 这能回答你的问题吗? SQL to LINQ Tool
  • var ProductId = "Yarn"; 产品 id 看起来像示例数据中的数字
  • 对不起。没有正确粘贴!
  • 我不知道为什么人们总是想将 SQL 转换为 linq。 SQL 是比 linq 更好的查询数据库工具。 Linq 尤其是在与 EF 一起使用时往往会破坏您的查询,使其难以优化。
  • @Liam - 试图在这里找到我的路。我对 SQL 更满意,但似乎使用 .net 和 EF,linq 有一些优势stackoverflow.com/questions/593808/…

标签: c# sql linq


【解决方案1】:

我认为这应该是等效的:

var productType = "Yarn";
var productId = 2835;
var query =
    from st in ctx.StockDetails
    where st.ProductType == productType
    where st.ProductId == productId
    orderby st.CreationDate descending
    let suppliers =
        from suo in ctx.SupplierOrders
        join su in ctx.Suppliers on suo.SupplierId equals su.Id
        where suo.Id == st.SupplierCmdId
        select su
    from su in suppliers.DefaultIfEmpty()
    select new
    {
        st.ProductId,
        st.ProductType,
        st.StockValue,
        st.InOut,
        st.SupplierCmdId,
        st.CreationDate,
        SupplierId = su.Id,
    };

【讨论】:

  • 感谢@Jeff Mercado。它给了我一个 CS1941 C# join 子句中的一个表达式的类型不正确。调用“加入”时类型推断失败。
  • 我必须在 where 子句之前将 let 向上移动,它工作得很好。再次感谢@Jeff Mercado
猜你喜欢
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2022-01-20
  • 2014-08-14
  • 1970-01-01
相关资源
最近更新 更多