我有一个雇员类,从数据库中提取。在该Employee类中,我想基于Employee数据库中的managerCode添加一个Manager对象,该对象也是一个Employee。请参阅下面的课程。包含内部项目时返回JSon
managerCode未被定义为关键字。我不需要递归,也就是说我不需要经理的经理等。只有一个层次,员工和他的经理。
使用.NET 4.5,C#,OData的V4
我使用的OData发回的员工,但管理部分未在响应加入,即使它的存在在我尝试发送对象。
我错过了什么? WebApiConfig中的东西?
谢谢
雇员类,前4个字段直接从数据库中获取。
Class Employee
{
[Key]
public int id { get; set; }
public string employeeCode { get; set; }
public string employeeName { get; set; }
public string managerCode { get; set; }
[NotMapped]
public Employee Manager { get; set; }
}
控制器类。 GetEmployeeById(id)将获得员工的经理。
[HttpGet]
[EnableQuery]
[ODataRoute("employeeById(id={id})")]
public IHttpActionResult employeeById([FromODataUri]int id)
{
var sets = dbContext.GetEmployeeById(id);
if (!sets.Any())
return NotFound();
return this.CreateOKHttpActionResult(sets);
}
WebApiConfig
public static void Register(HttpConfiguration config)
{
config.MapODataServiceRoute("ODataRoute", "odata",GetEdmModel(),
new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.Namespace = "employee_odata";
builder.ContainerName = "employee_odataContainer";
builder.EntitySet<Employee>("Employee");
builder.EnableLowerCamelCase();
var unboundGetEmployee = builder.Function("employeeById");
unboundGetEmployee.Returns<Employee>();
unboundGetEmployee.Parameter<int>("id");
unboundGetEmployee.Namespace = "employee_odata.Functions";
return builder.GetEdmModel();
}
SOLUTION从WebApiConfig删除unboundGetEmployee
(不需要)
。在Employee类的虚拟
制作经理项目,未经[NotMapped]
:
public virtual Manager Manager { get; set; }
控制器:
[EnableQuery]
[ODataRoute("Employee({id})")]
public IHttpActionResult employeeById([FromODataUri]int id)
{
//handle data return normally...
//I have to detect $expand=Manager, to fetch the actual Manager object.
//otherwise it's null (not linked with primary key)
}
有了这些费用的变化,$展开运作良好。
感谢您对Get()的回答和建议。但是,$ expand = Manager不起作用,它给了我_«在类型'Models.Employee'»_上找不到名为'Manager'的属性。任何想法? – user1482939
解决了它。见上面的更新。这是几件小事的组合。 – user1482939