【问题标题】:Linq To Sql Join with multiple conditions and tableLinq To Sql Join 与多个条件和表
【发布时间】:2021-08-12 01:11:33
【问题描述】:

我怎样才能将此 sql 转换为 Linq 到 sql

SELECT   v.Id, c.Id, bt.*
FROM BankTransaction bt
LEFT OUTER JOIN Customer c ON (bt.ObjectId = c.Id And bt.TransactionForObjectId = 1)
LEFT OUTER JOIN Vendor v ON (bt.ObjectId = v.Id And bt.TransactionForObjectId = 2)
LEFT OUTER JOIN AccountTitle ac ON (bt.ObjectId = ac.Id And bt.TransactionForObjectId = 3)

【问题讨论】:

  • 到目前为止你有什么收获?
  • 我正在尝试不同的 linq to sql 查询,但没有得到结果
  • @Charlieface 检查我目前正在尝试的答案。
  • 也许我的SQL to LINQ Recipe 可以帮助你。更具体地说,join c in Customer on new { bt.ObjectId, bt.TransactionForObjectId } equals new { ObjectId = c.Id, TransactionForObjectId = 1 } into cj from c in cj.DefaultIfEmpty()
  • @NetMage 不,不是。

标签: sql sql-server entity-framework linq linq-to-sql


【解决方案1】:

这是我目前正在尝试的

var tran = await (
                        from bankTrans in InventoryContext.BankTransaction.Where(x => x.BankId == bank.Id && x.Date <= BankTransaction.Date)
                        from ven in InventoryContext.Vendor.Where(x => bankTrans.ObjectId == x.Id && bankTrans.TransactionForObjectId == (int)TransactionFor.Vendor)
                        .DefaultIfEmpty()
                        from cus in InventoryContext.Customer.Where(x => bankTrans.ObjectId == x.Id && bankTrans.TransactionForObjectId == (int)TransactionFor.Customer)
                        .DefaultIfEmpty()
                        from other in InventoryContext.AccountTitle.Where(x => bankTrans.ObjectId == x.Id && bankTrans.TransactionForObjectId == (int)TransactionFor.Other)
                        .DefaultIfEmpty()
                        select new
                        { bankTrans, ven, cus, other, cash }).ToListAsync();

【讨论】:

  • 你得到了什么结果?您在这里有额外的过滤器,这些过滤器不在 SQL 版本Where(x =&gt; x.BankId == bank.Id &amp;&amp; x.Date &lt;= BankTransaction.Date)
  • @Charlieface 让我们在没有 where 子句的情况下尝试过这个,但没有得到想要的结果。
  • @SvyatoslavDanyliv 返回 null。
猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 2019-04-04
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
相关资源
最近更新 更多