简而言之: 总结这个问题的一种更简单的方法是,你能在 linq 的连接上应用条件吗?
我有以下 sql 查询:
select cdm.cashID, cdm.DateTimeTillOpened, cdm.DateTimeTillClosed, o.OrderID, o.OrderDate
from CashDrawsMonies cdm
join Orders o on o.OrderDate >= cdm.DateTimeTillOpened
AND o.OrderDate <= cdm.DateTimeTillClosed
join Users u on o.UserID = u.UserID
where u.UserID = 'C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A'
group by cdm.cashID, cdm.DateTimeTillOpened, cdm.DateTimeTillClosed, o.OrderID, o.OrderDate
order by o.OrderDate desc
替代 SQL@
select *
from CashDrawsMonies cdm
where exists
(
select *
from Orders o
join Users u on o.UserID = u.UserID
where
o.OrderDate >= cdm.DateTimeTillOpened and
o.OrderDate <= cdm.DateTimeTillClosed and
u.UserID = 'C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A'
)
我可以转换大多数查询,但在 Linq 中的连接上,它总是要求一个相等的关键字,而不是像 >= 或 <= 这样的东西,它允许我在 sql 中对连接设置一个条件。这就是让我挠头的原因,我该如何转换它呢?
我在代码(c#)中的 linq-To-Entites 模型设置为:
Cache.Model.Orders
Cache.Model.CashDrawMonies
Cache.Model.Users
感谢帮助。
尝试1:
var results = from o in Cache.Model.Orders
from c in Cache.Model.CashDrawMoneys
join u in Cache.Model.Users on o.UserID equals u.UserID
where c.DateTimeTillOpened >= o.OrderDate
&& c.DateTimeTillClosed <= o.OrderDate
select c;
尝试2:
var results = from c in Cache.Model.CashDrawMoneys
from o in Cache.Model.Orders
where c.DateTimeTillOpened >= o.OrderDate
&& c.DateTimeTillClosed <= o.OrderDate
group c by new { c.cashID, c.DateTimeTillOpened, c.DateTimeTillClosed, o.OrderID, o.OrderDate, o.UserID } into temp
from t in temp
join u in Cache.Model.Users on t.UserID equals u.UserID
where t.UserID == selectedUser.UserID
select t;
不返回任何结果....:S
更新:
我重新编写了我的 sql,第二段 sql 正是我想知道的。只是需要有人以某种方式为我转换它???
使用 Linqer 转换的 SQL 版本 2:
from cdm in db.CashDrawMoneys
where
(from o in db.Orders
join u in db.Users on o.UserID equals u.UserID
where
o.OrderDate >= cdm.DateTimeTillOpened &&
o.OrderDate <= cdm.DateTimeTillClosed &&
u.UserID == new Guid("C3763CC6-D1C5-4EF3-9B83-F7AB3BF8827A")
select new {
o,
u
}).FirstOrDefault() != null
select new {
cdm.UserID,
cdm.DateTimeTillClosed,
cdm.DateTimeTillOpened,
cdm.LooseChange,
cdm.Fivers,
cdm.Tens,
cdm.Twenties,
cdm.Fifties,
cdm.IsOpen,
cdm.IsClosed,
cdm.ClosingValue,
cdm.OpeningValue,
cdm.cashID
}
编译 nbut 会产生以下错误:
“DbIsNullExpression 的参数必须引用原始类型或引用类型。”