C# Linq 查询问题

您好,我正在尝试按 ID 检索特定部门。


这是我的代码


public void GetDeptId(int _DeptID)

{

var dept = dbContext.tblDepartments

    .Select(d => new Department

    {

        DepartmentID = d.DepartmentID,

        DepartmentName = d.DepartmentName

    }).Where(d => d.DepartmentID == _DeptID);

}

如何根据 _DeptID 过滤结果集?即使记录存在,这也不会返回任何记录。


富国沪深
浏览 83回答 3
3回答

慕桂英3389331

您需要 Select 子句吗?如果你只需要检索一个部门,你可以这样做:public void GetDeptId(int _DeptID){     var depts = dbContext.tblDepartments                         .Where(d => d.DepartmentID == _DeptID);}或者,如果它只是一个,这将是有意义的:public void GetDeptId(int _DeptID){     var dept = dbContext.tblDepartments                         .First(d => d.DepartmentID == _DeptID);}

MYYA

做这样的事情:&nbsp; public ICollection<Department> GetDeptId(int _DeptID){var dept = dbContext.tblDepartments&nbsp; &nbsp; .Select(d => new Department&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DepartmentID = e.DepartmentID,&nbsp; &nbsp; &nbsp; &nbsp; DepartmentName = e.DepartmentName&nbsp; &nbsp; }).Where(c => c.DepartmentID == _DeptID).ToList();&nbsp;return dept;}

至尊宝的传说

请试试这个。var dept = dbContext.tblDepartments.Where(d => d.DepartmentID == _DeptID)&nbsp; &nbsp; .Select(d => new Department&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DepartmentID = d.DepartmentID,&nbsp; &nbsp; &nbsp; &nbsp; DepartmentName = d.DepartmentName&nbsp; &nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP