简体   繁体   English

如何从linq中的select new子句中选择记录

[英]How to select record from select new clause in linq

I have the following code I am having 3 tables as Department, DepartmentTask and DepartmentPosition. 我有以下代码,我有3个表,分别是Department,DepartmentTask和DepartmentPosition。 Here are the tables : 这是表格:

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; }       
}

So any department can be a parent to another department, Task and Position. 因此,任何部门都可以成为另一个部门(任务和职位)的父级。 So here I want to select all the records from the tables which are children of a particular Department based on DepartmentId. 因此,在这里我想根据DepartmentId从表中选择所有记录,这些记录是特定部门的子级。

var z = from n in dbbs.Department
        select new
        {
            deptcount = dbbs.Department.Count(p => p.ParentDepartmentId == id),
            poscount = dbbs.DepartmentPosition.Count(x => x.DepartmentId == id),
            taskcount = dbbs.DepartmentTask.Count(t => t.DepartmentId == id)
        };
if(z.Count()>0)
{ 
//do something
}
else
{

}

and now if there are no record within tables still it is coming within if block. 现在,如果表中没有记录,它仍在if块中。 I want to know how to restrict if there are no records as per the query. 我想知道如何限制是否没有根据查询的记录。

I'm not sure what you are trying to achieve with the select statement. 我不确定您要使用select语句尝试实现什么。 Can you not use: 你不能使用:

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
}

if you are trying to do a grouping based on the departments please explain and I'll update my answer. 如果您尝试根据部门进行分组,请解释,我将更新答案。

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()
                              };

then 然后

if(count.tbl1count.any()){
//do whatever you need}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM