如何才能完成。 sql是用Linq编写的。我正在使用LinqToEntities,C#。 @companyID& @branchID是参数
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.我哪里错了。
答案 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);
答案 1 :(得分: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();