Reputation: 6159
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.
Upvotes: 3
Views: 1509
Reputation: 6159
This did the trick
var result = queryOptions
.ApplyTo(test, new ODataQuerySettings
{
HandleNullPropagation =
HandleNullPropagationOption.True
}, null)
.Cast<TestDTO>();
return Json(result);
Upvotes: 1