Piz*_*000 4 c# odata asp.net-web-api
我正在尝试使用 Web API 通过 OData v4 服务公开只读计算属性。我的搜索只出现 2014 年或更早的帖子,唯一的解决方案要么是过时的代码,要么是 OData 的下一个版本将支持计算属性的承诺(我确信从那时起已经有一些“下一个版本”) )。
对于我的示例,我将使用一个Person带有组合的类FullName:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// My calculated property.
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的WebAPIConfig:
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using TestService.Models;
namespace TestService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("People");
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前,JSON 不显示FullName. 在当前情况下需要做什么才能做到这一点?
编辑:为我的对象添加控制器Person:
using System.Web.Http;
using System.Web.OData;
using TestService.Models;
namespace TestService.Controllers
{
public class PeopleController : ODataController
{
DataContext db = new DataContext();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Person> Get()
{
return db.People;
}
[EnableQuery]
public SingleResult<Person> Get([FromODataUri] int key)
{
IQueryable<Person> result = db.People.Where(p => p.ID == key);
return SingleResult.Create(result);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我通过另一个答案找到了答案。对于你的情况,我认为代码看起来像这样:
namespace TestService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("People");
// Added this:
builder.StructuralTypes.First(t => t.ClrType == typeof(Person))
.AddProperty(typeof(Person).GetProperty(nameof(Person.FullName)));
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
}
}
}
Run Code Online (Sandbox Code Playgroud)
这对我在 .NET Core 3.1 和最新的 WebApi 和 OData 库上有用(我认为)。
请注意,如果您的模型是基于 EF 的,您还需要[NotMapped]该属性来防止模型崩溃。
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |