Mehmet
Mehmet

Reputation: 1874

Entity class serialize to json

       try
        {
            using (EXAMINATIONEntities entity = new EXAMINATIONEntities())
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var exams = entity.TBL_EXAMS.Where(x => x.USERID == userId);                    
                return serializer.Serialize(exams);
            }
        }
        catch (Exception ex)
        {
            return "-1";
            throw ex;
        }

This code works fine. But returns a json string like this;

[{"EXAM_ID":1,"EXAM_TEXT":"sdf","EXAM_ORDER":1,"SITUATION":true,"USERID":100,"DBDATETIME":null,"TBL_QUESTIONS":[],"EntityState":2,"EntityKey":{"EntitySetName":"TBL_EXAMS","EntityContainerName":"EXAMINATIONEntities","EntityKeyValues":

I want to serialize just table fields : "EXAM_ID":1,"EXAM_TEXT":"sdf","EXAM_ORDER":1,"SITUATION":true,"USERID":100,"DBDATETIME":null

but it serilezes all entity class fields and properties.. How can I serialize which entity class field I want to seriaize?

Upvotes: 0

Views: 1751

Answers (1)

jrummell
jrummell

Reputation: 43097

You can project only the properties you want to an anonymous type:

JavaScriptSerializer serializer = new JavaScriptSerializer();
var exams = entity.TBL_EXAMS.Where(x => x.USERID == userId)
           .Select(exam => new {
                      exam.EXAM_ID, exam.EXAM_TEXT, exam.EXAM_ORDER /* etc */
                   });                    
return serializer.Serialize(exams);

Upvotes: 2

Related Questions