我为移动应用程序准备了 Odata API,但 $Expand 存在问题。当我使用这个查询时,一切正常。
查询: .../odata/forms?$expand=FormFields($expand=FormFieldRadios)&$filter=FormId eq 1
但是当我使用这个查询时:
.../odata/forms(1)?$expand=FormFields($expand=FormFieldRadios)
展开不起作用,项目集合为空。
我的 json 结果 Items coolection One item
配置服务:
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);
配置
app.UseMvc(routeBuilder =>
{
routeBuilder.Select().Expand().Filter().Count().OrderBy().MaxTop(250).Expand(QueryOptionSetting.Allowed);
routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
});
模型构建器
builder.EntitySet<Form>("Forms").EntityType.Filter().Count().Expand(OdataDefaults.MaxExpansionDepth).OrderBy().Page().Select();
表单实体
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 的 Find
方法不返回 IQueryable<TEntity>
而是TEntity
本身。因此,OData 无法再对其进行扩展是合乎逻辑的,因为不再需要“修改”表达式树。
将您的功能更改为:
[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)));
}
关于.net - 当我得到一件商品时 $Expand 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57358424/