user1431633
user1431633

Reputation: 658

Return only certain columns to JSON in LINQ

I don't want to return the entire table in the JSON. I only want the following columns: ProjectContactFirstName, ProjectContactLastName but nothing I try works. Here's my code:

[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!
    }
}

Upvotes: 1

Views: 2779

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You have to filter the columns before passing object to serializer:

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

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Use Select method to project your project entity to anonymous object with ProjectContactFirstName and ProjectContactLastName properties:

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

This kind of projection has one benefit - it occurs on database side, and only these two fields will be loaded from database. Serialization of anonymous object will give you columns which you selected during projection.

BTW Thus you are selecting project(s) by id, maybe you need to use FirstOrDefault() instead of ToList()?

Upvotes: 1

Related Questions