Odata Asp.NET WebApi返回entity / DTO

时间:2015-11-11 13:53:49

标签: c# json serialization asp.net-web-api odata

我的实体QueryFilter有一个属性,其中包含序列化的json。 在QueryFilterDetailDTOController中我想反序列化JSON,用一些数据丰富它并返回带有新JSON数据的DTO。

我希望能够直接使用丰富的JSON对象作为javascript中返回对象的属性(而不是字符串)。我怎样才能做到这一点?

我尝试将表达式类型设置为JObject,但是模型构建器会抛出异常(因为递归类型)。这是正确的方法,还是有更好的方法?

DTO

public class QueryFilterDetailDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Context { get; set; }
    public JObject Expression { get; set; }

    public QueryFilterDetailDTO(QueryFilter queryFilter)
    {
        ID = queryFilter.ID;
        Name = queryFilter.Name;
        Description = queryFilter.Description;
        Context = queryFilter.Context;
    }
}

控制器

public class QueryFilterDetailDTOController : ODataController
{
    private readonly IQueryFilterService _service;

    public QueryFilterDetailDTOController(IQueryFilterService service)
    {
        _service = service;
    }

    [HttpGet]
    [EnableQuery(MaxNodeCount = 1000)]
    public HttpResponseMessage Get([FromODataUri] int key)
    {
        var queryFilter = _service.Find(key);

        var dto = new QueryFilterDetailDTO(queryFilter);
        dto.Expression = JObject.Parse(queryFilter.SerializedFilter);
        dto.Expression["Test"] = 1;

        return Request.CreateResponse(HttpStatusCode.OK, dto);    
    }
}

创建模型

private static IEdmModel GetModel()
{
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<QueryFilterDetailDTO>("QueryFilterDetailDTO").EntityType.HasKey(dto => dto.ID);
    builder.GetEdmModel();
}

1 个答案:

答案 0 :(得分:0)

You should be able to use JsonExtensionData for this purpose:

public class QueryFilterDetailDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Context { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> Expression { get; set; }
}

The extension data holds keys and values for any JSON properties that could not be mapped to c# properties.

For more details see here and here.