C#seralize动态对象与EF结果(从动态c#对象创建JSON对象)

时间:2016-12-19 11:08:05

标签: c# json entity-framework serialization dynamic

我有这段代码:

var companyDetails = db.tbl_Mallstore.ToList();

dynamic result = new System.Dynamic.ExpandoObject();
result.count = 1;
result.company = companyDetails.FirstOrDefault();

JavaScriptSerializer serializer = new JavaScriptSerializer();

string output = serializer.Serialize(result);

抛出错误:

  

序列化“eDurar.Models.tbl_Mallstore”类型的对象时检测到循环引用

在这种情况下,它有效:

dynamic result = new System.Dynamic.ExpandoObject();
result.count = count;
result.store_name = companyDetails.FirstOrDefault().store_name;

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(result);

1 个答案:

答案 0 :(得分:0)

我必须手动指定所需的字段。我认为其他数据中有一些循环引用。

int count = 0;

var companyDetails = db.tbl_Mallstore.ToList();

count = companyDetails.Count();

dynamic result = new System.Dynamic.ExpandoObject();
result.count = count;
if (count > 0)
{
    result.store = companyDetails.Select(x => new { x.store_name, x.store_id }).FirstOrDefault();
}

return this.Json(result);