簡而言之: 一個簡單的總結這個問題的方法是,你可以在linq中的連接上應用一個條件嗎?無法將SQL查詢轉換爲等效的LinqToEntities代碼?
我有以下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中給連接添加條件。這是什麼讓我撓我的頭,然後如何轉換它呢?
我的LINQ到entites的代碼(C#)模型建立爲:
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
UPDATE:
我重新寫我的SQL,SQL的第二peiece確實我想知道到底是什麼。只需要某人爲我轉換它不知何故?
SQL版本2轉換使用Linqer:
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
}
編譯n但產生以下錯誤:「到DbIsNullExpression的參數必須指原語或引用類型」
謝謝,這接近我設法得到我自己:) – IbrarMumtaz