C# 如何从linq中的select new子句中选择记录
我有以下代码 我有3张表,分别是部门、部门任务和部门职位。以下是表格:C# 如何从linq中的select new子句中选择记录,c#,linq,C#,Linq,我有以下代码 我有3张表,分别是部门、部门任务和部门职位。以下是表格: public partial class Department() { public int DepartmentId { get; set; } public string DepartmentName { get; set; } public Nullable<int> ParentDepartmentId { get; set; } } public partial class D
public partial class Department()
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public Nullable<int> ParentDepartmentId { get; set; }
}
public partial class DepartmentPosition
{
public int PositionId { get; set; }
public int DepartmentId { get; set; }
public string PositiontName { get; set; }
}
public partial class DepartmentTask
{
public int TaskId { get; set; }
public int DepartmentId { get; set; }
public string TaskName { get; set; }
}
现在,如果表中没有记录,它仍然在if块中。我想知道如何根据查询限制是否没有记录。我不确定您试图通过select语句实现什么。你不能使用:
var deptcount = dbbs.Department.Count(p => p.ParentDepartmentId == id);
var poscount = dbbs.DepartmentPosition.Count(x => x.DepartmentId == id);
var taskcount = dbbs.DepartmentPosition.Count(t => t.DepartmentId == id);
if(deptcount > 0)
{
//do something
}
如果你想根据部门进行分组,请解释,我会更新我的答案
var count= from s in ObjectContext.tb1
join c in ObjectContext.tb2 on s.ParentCategoryID equals c.PersonCategoryID
join p in ObjectContext.tb3 on c.BusinessEntityID equals p.BusinessEntityID
select new count()
{
tbl1count =c.count()
tbl2count =p.count()
tbl3count =p.count()
};
然后
让我猜一猜,它返回的对象在z内的计数为0?这是一个非常奇怪的查询-您根本没有使用n。你到底想达到什么目的?为什么有两个属性poscount和taskcount的计数完全相同?@JonSkeet我有3个表。Department表记录可以是其余表的父级,也可以是表本身的父级。现在,我的想法是检查哪个表有子记录,而父记录是来自部门的记录。那么为什么不进行三个单独的计数查询呢?现在还不清楚为什么你的两个查询是相同的……如果我有7个表,那么我需要写7个查询吗?是否有其他的sol。谢谢,正如乔恩在上面所说的,这取决于你想要实现什么。你真的需要解释得足够详细,我们才能帮助你。你能解释一下,如果你在数据库中这样做,你希望得到什么以及你有什么表吗?看看这个var query=from p in parentable join c in childatable 1 on c.foreign id equals p.id join c2 in childatable2 on c.foreign id equals p.id
var count= from s in ObjectContext.tb1
join c in ObjectContext.tb2 on s.ParentCategoryID equals c.PersonCategoryID
join p in ObjectContext.tb3 on c.BusinessEntityID equals p.BusinessEntityID
select new count()
{
tbl1count =c.count()
tbl2count =p.count()
tbl3count =p.count()
};
if(count.tbl1count.any()){
//do whatever you need}