简体   繁体   中英

Odata Asp.NET WebApi return json property in entity/DTO

My Entity QueryFilter has a property, that contains serialized json. In QueryFilterDetailDTOController I want to deserialize the JSON, enrich it with some data and return a DTO with the new JSON data.

I want to be able to consume the enriched JSON Object directly as a property of the returned object in javascript (not as string). How can I achieve this?

I tried to set the Type of Expression to JObject , but the model builder it throws an exception (because of the recursive Type). It this the correct approach, or is there a better way?

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

Controller

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

Create Model

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM