简体   繁体   中英

OData in .NET Core Web API Serialization for List / Dictionary

I'm using .NET Core 2.0.0 with https://www.nuget.org/packages/microsoft.aspnetcore.odata

This is my setup so far.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddOData();
    services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel);
    ...
}

private ODataModelManager DefineEdmModel(IServiceProvider services)
{
    var modelManager = new ODataModelManager();

    var builder = new ODataConventionModelBuilder();
    builder.EntitySet<TestDTO>(nameof(TestDTO));
    builder.EntityType<TestDTO>().HasKey(ai => ai.Id); // the call to HasKey is mandatory
    modelManager.AddModel(nameof(Something), builder.GetEdmModel());

    return modelManager;
}

public void Configure(...)
{
    ...
    var modelBuilder = new ODataConventionModelBuilder();
    modelBuilder.EntitySet<TestDTO>("TestDTOs");

    app.UseMvc(builder =>
    {
        builder.MapODataRoute("api", modelBuilder.GetEdmModel());
    });
    ...
}

Controller

[HttpGet("all")]
public async Task<IQueryable<TestDTO>> Get()
{
    // plug your entities source (database or whatever)
    var test = await TestService.GetTest();

    var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger));
    var model = modelManager.GetModel(nameof(Something));
    var queryContext = new ODataQueryContext(model, typeof(TestDTO), null);
    var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request, Provider);

    return queryOptions
        .ApplyTo(test, new ODataQuerySettings
        {
            HandleNullPropagation = HandleNullPropagationOption.True
        }, null)
        .Cast<TestDTO>();
}

Model

public class TestDTO : BaseEntityDTO
{
    [Required]
    public Guid Id { get; set; }
    public List<CustomerDTO> Customers { get; set; }
    public List<string> Tags { get; set; }
    [JsonExtensionData]
    public IDictionary<string, object> AddProperties { get; set; }
}

The problem is that with services.AddOData(); i only get return results with property Id, without services.AddOData(); I get all the properties json formatted.

How do I serialize also the List properties and maybe the Dictionary aswell?

Thanks.

This did the trick

var result = queryOptions
                         .ApplyTo(test, new ODataQuerySettings
                         {
                             HandleNullPropagation = 
                             HandleNullPropagationOption.True
                          }, null)
                          .Cast<TestDTO>();
return Json(result);

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