在json.net中处理实体框架关系

时间:2012-10-25 07:56:24

标签: entity-framework asp.net-web-api json.net

我有一个ASP MVC Web Api项目,它使用json.net输出json。我有以下模型:

public class ModelA
{
    public int Id {get;set;}
    public string Name {get;set;}

    [JsonIgnore]
    public int TypeModelId {get;set;}
    public virtual TypeModel TypeModel {get;set;}
}

public class TypeModel
{
    [JsonIgnore]
    public int Id {get;set;}

    public string Name {get;set;}

    [JsonIgnore]
    public virtual IList<ModelA> ModelAs {get;set;}
}

当我序列化ModelA时,输出将是这样的:

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": {
      "Name": "testtype1"
    }
  }
]

是否可以使用json.net获得这样的输出..

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": "testtype1"
  }
]

..还是我必须将ModelA的内容复制到一个新的类,该类将TypeModel关系存储为字符串而不是引用?也许有更好的解决方案?

2 个答案:

答案 0 :(得分:1)

正如您所说,唯一的方法是使用DTO。这是因为,正如您所指出的,TypeModel的类型是类TypeModel而不是字符串。如果您使用Linq,您也可以通过以下方式使用匿名类型。

return db.ModelAs.Single(x=>x.Id == id).Select(x=> new{
    x.Id,
    x.Name,
    TypeModel = x.TypeModel.Name
});

答案 1 :(得分:0)

实际上这不是真的,json.net可以处理循环引用处理,dto是一个旧方法,仍然很好,但你可以在序列化程序中启用处理循环引用的选项,只要它是mvc5,也可能是mvc4。 更多详情:https://stackoverflow.com/a/23044770/1345207