将实体转换为自定义格式

时间:2014-02-21 12:33:32

标签: c# linq entity-framework linq-to-sql

我有一个转换为JSON的模型。为了减少数据量,我用id替换任何父实体。以前我这样做过:

JsonConvert.SerializeObject(from program in context.Programs select new {
  id = program.id,
  name = program.name,
  parent_id = program.parent.id
});

但由于我需要在多个地方执行此操作,因此我在模型中添加了ToJSON函数:

public class ProgramModel
{
    [Key, Column(Order = 1)]
    public int? id { get; set; }

    [Required, Key, Column(Order = 2)]
    public virtual ParentModel parent { get; set; }

    [Required, MaxLength(128)]
    public string name { get; set; }

    public object ToJSON()
    {
        return new
        {
            id = id,
            name = name,
            parent_id = parent.id
        };
    }
}

然后我像这样使用它:

JsonConvert.SerializeObject(from program in context.Programs select program.ToJSON());

哪个不起作用,让我回答我的问题。如何以避免代码重复的方式执行上述操作?

上述行抛出的异常:

  

System.NotSupportedException:LINQ to Entities无法识别方法'System.Object ToJSON()'方法,并且此方法无法转换为商店表达式。

3 个答案:

答案 0 :(得分:1)

你不需要只使用LINQ,记住好的'foreach

List<object> objs = new List<object>();

foreach (var program in context.Programs)
{
    objs.Add(program.ToJSON());
}

JsonConvert.SerializeObject(from program in objs select program);

答案 1 :(得分:0)

试试这个

添加“using System.Web.Script.Serialization;”命名空间

然后在实体类

public class ProgramModel
    {
        [Key, Column(Order = 1)]
        public int? id { get; set; }

        [Required, Key, Column(Order = 2)]
        public virtual ParentModel parent { get; set; }

        [Required, MaxLength(128)]
        public string name { get; set; }

        public object ToJSON()
        {

                JavaScriptSerializer oSerializer = new JavaScriptSerializer();
                string sJSON = oSerializer.Serialize(this);
                return sJSON;
                //id = id,
                //name = name,
                //parent_id = parent.id

        }
    }

要在Page_Load()

中测试一下
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ParentModel prmodel = new ParentModel();
                prmodel.id = 5;
                List<ProgramModel> listdata = new List<ProgramModel>();
                ProgramModel data = new ProgramModel();

                data.id = 7;
                data.parent = prmodel;
                data.name = "program";
                listdata.Add(data);

                var jsdata = from program in listdata select program.ToJSON();

            }
        }

答案 2 :(得分:0)

异常是因为Linq-Entities无法将ToJSON()方法转换为sql命令

你可以试试这个

   //first get all the items using Linq-Entities
     var programs = (from program in context.Programs select program).ToList();

     //use foreach on the list
     programs.ForEach(program =>
            {
                JsonConvert.SerializeObject(program.ToJSON());
            });