I prepare Odata API for mobile application, and i have a problem with $Expand. When i use this query everything works ok.
Query: .../odata/forms?$expand=FormFields($expand=FormFieldRadios)&$filter=FormId eq 1
But when i use this query:
.../odata/forms(1)?$expand=FormFields($expand=FormFieldRadios)
Expand does not work and items collection si empy.
My json results Items coolection One item
ConfigureServices:
services.AddOData();
services.AddODataQueryFilter();
services.AddMvc(options =>
{
// https://blogs.msdn.microsoft.com/webdev/2018/08/27/asp-net-core-2-2-0-preview1-endpoint-routing/
options.EnableEndpointRouting = false;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Configure
app.UseMvc(routeBuilder =>
{
routeBuilder.Select().Expand().Filter().Count().OrderBy().MaxTop(250).Expand(QueryOptionSetting.Allowed);
routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
});
ModelBuilder
builder.EntitySet<Form>("Forms").EntityType.Filter().Count().Expand(OdataDefaults.MaxExpansionDepth).OrderBy().Page().Select();
Form Entity
public class Form
{
[Key, Required]
public int FormId { get; set; }
[Required]
public int Order { get; set; }
[Required]
public bool Active { get; set; }
[Required, MaxLength(255)]
public string Name { get; set; }
public int IsDeleted { get; set; }
[MaxLength(255)]
public string SuccessMessage { get; set; }
public ICollection<FormField> FormFields { get; set; } = new List<FormField>();
}
Odata Controller
public class FormsController : ODataController
{
private VillageContext _db;
public FormsController(VillageContext context)
{
_db = context;
}
[EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
public IActionResult Get()
{
return Ok(_db.Forms);
}
[EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
public IActionResult Get([FromODataUri] int key)
{
return Ok(_db.Forms.Find(key));
}
}
EntityFramework's Find
method does not return an IQueryable<TEntity>
but rather TEntity
itself. It is therefore logical that OData can no longer expand on it, since there is no expression tree anymore to "modify".
Change your function to this:
[EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
public IActionResult Get([FromODataUri] int key)
{
return Ok(SingleResult.Create(_db.Forms.Where(form => form.FormId == key)));
}