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

这段代码工作正常。但是返回一个像这样的json字符串;

[{"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":

我只想序列化表字段: "EXAM_ID":1,"EXAM_TEXT":"sdf","EXAM_ORDER":1,"SITUATION":true,"USERID":100,"DBDATETIME":null

但它会序列化所有实体类字段和属性。如何序列化我想要序列化的实体类字段?

4

1 回答 1

2

您只能将您想要的属性投影到匿名类型:

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);
于 2012-05-30T19:52:35.900 回答