2013-12-15 48 views
1

怎樣才能在foll。 sql可以寫在Linq中。我正在使用LinqToEntities,C#。 @companyID & @branchID是參數linq空條件

select * from tblEmp e 
where e.deleted = 0 and 
(e.companyId = @companyID OR e.companyid is null) and 
(e.branchId = @branchID OR e.branchid is null) 

現在,有一個相同的存儲過程,我使用它在LINQ,就像這樣:

var qry = from d in MYDB.GetData(int companyid, int branchid) 
select new 
{ 
//all reqd. columns... 
} 

那麼,有沒有可能直接寫在Linq上面。

編輯:

public IEnumerable<tblEmp> GetData(Guid gCID, Guid gBID) 
{ 
    var employees = (from e in tblEmp 
       where !e.deleted 
       && (e.companyId == gCID || e.companyid == null) 
       && (e.branchId == gBID || e.branchid == null) 
       select e 
       ).AsEnumerable(); 
} 

//參數都是 '00000000-0000-0000-0000-000000000000'。我期待所有的記錄,但計數是0.我哪裏錯了。

回答

2

肯定的:

var employees = (from e in tblEmp 
       where !e.deleted 
       && (e.companyId == aCompanyIdHere || e.companyid == null) 
       && (e.branchId == aBranchIdHere || e.branchid == null) 
       select new 
       { 
        e.Id, 
        e.companyId, 
        e.branchId 
       }); 

編輯

查詢應該工作,但我懷疑你的要求是有點不同。 如果您想在傳入的參數Guid爲空時獲取所有項目,則可以執行以下操作。

public IEnumerable<tblEmp> GetData(Guid gCID, Guid gBID) 
{ 
    var employees = (from e in tblEmp 
        where !e.deleted 
        && (gCID == Guid.Empty || e.companyid == gCID) 
        && (gBID == Guid.Empty || e.branchid == gBID) 
        select e 
        ).AsEnumerable(); 
} 

但更好的可讀性IMO:

public IEnumerable<tblEmp> GetData(Guid? gCID, Guid? gBID) 
{ 
    var employees = (from e in tblEmp 
        where !e.deleted 
        && (gCID == null || e.companyid == gCID) 
        && (gBID == null || e.branchid == gBID) 
        select e 
        ).AsEnumerable(); 
} 

,並傳遞null而不是Guid.Empty如果你想要的所有記錄。

var data = GetData(null, null); 
+0

謝謝。如果數據類型是guid而不是int,這會工作嗎?在DB中有記錄,但是我得到0個計數。我已經更新了我的問題,我嘗試過了。 – Ruby

+0

@Ruby我已經更新了我的答案。 – Silvermind

+0

非常感謝。我發現第一個更可讀:) – Ruby

1
var qry = (
    from test in MYDB.tblEmp 
    where !e.deleted 
     && (e.companyId == "any id" || e.companyid == null) 
     && (e.branchId == "anyid" || e.branchid == null) 
    select test 
).FirstOrDefault(); 
+0

也許你意外地是對的,但我在任何地方都沒有在他的查詢中看到「TOP 1」。 – Silvermind