Linq代码不会返回正确的记录

DFo*_*k42 2 c# linq

我有一个以dbo.EmployeeType三条记录命名的表:

PK_EmployeetypeID    EmployeeTypeName 
1                    Project Manager 
2                    Business Analyst 
3                    Developer
Run Code Online (Sandbox Code Playgroud)

我有这段Linq代码:

public static string GetTypeByID(int id)
{
    using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
    {
        var type = db.EmployeeTypes.Select(o => new LOOKUPEmployeeType
        {
            PK_EmployeeTypeID = id,
            EmployeeTypeName = o.EmployeeTypeName
        });

        return type.FirstOrDefault().EmployeeTypeName;
    }
}
Run Code Online (Sandbox Code Playgroud)

无论我发送给它的id是什么,它都会返回Project Manager,我对于为什么感到困惑.

Dav*_*idG 7

您需要应用过滤器,否则您只需返回第一条记录并对ID进行硬编码.试试这个:

public static string GetTypeByID(int id)
{
    using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
    {
        //Here we apply a filter, the lambda here is what creates the WHERE clause
        var type = db.EmployeeTypes
            .FirstOrDefault(et => et.PK_EmployeeTypeID == id);

        if(type != null)
        {
            return type.EmployeeTypeName;
        }
        else
        {
            return "";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,FirstOrDefault如果没有匹配或多个匹配,type则使用表示null将返回一个空字符串.