在LINQ中仅将某些列返回给JSON

时间:2014-01-16 19:10:17

标签: c# asp.net json linq

我不想在JSON中返回整个表。我只想要以下列:ProjectContactFirstNameProjectContactLastName,但我尝试的无效。这是我的代码:

[WebMethod]
public static string getProjectByID(int id)
{
    using (dbPSREntities4 myEntities = new dbPSREntities4())
    {
        var thisProject = myEntities.tbProjects.Where(x => x.ProjectID == id).ToList();

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(thisProject); 

        return json; <--- here I need to say what columns to return but nothing will work. Thanks!
    }
}

2 个答案:

答案 0 :(得分:3)

在将对象传递给序列化程序之前,必须先过滤列:

[WebMethod]
public static string getProjectByID(int id)
{
    using (dbPSREntities4 myEntities = new dbPSREntities4())
    {
        var thisProject = myEntities.tbProjects.Where(x => x.ProjectID == id);

        var columns = thisProject.Select(x => new { x.ProjectContactFirstName, x.ProjectContactLastName }).ToList();

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(columns); 

        return json;
    }
}

答案 1 :(得分:1)

使用Select方法将项​​目实体投影到具有ProjectContactFirstName和ProjectContactLastName属性的匿名对象:

[WebMethod]
public static string getProjectByID(int id)
{
    using (dbPSREntities4 myEntities = new dbPSREntities4())
    {
        var thisProject = 
            myEntities.tbProjects
                      .Where(p => p.ProjectID == id)
                      .Select(p => new {
                           p.ProjectContactFirstName,
                           p.ProjectContactLastName
                       }).ToList();

        JavaScriptSerializer serializer = new JavaScriptSerializer();  
        var json = serializer.Serialize(thisProject);
        return json;
     }
}

这种投影有一个好处 - 它出现在数据库端,只有这两个字段将从数据库加载。匿名对象的序列化将为您提供在投影期间选择的列。

BTW因此,您正在按ID选择项目,也许您需要使用FirstOrDefault()代替ToList()