在OData v4控制器中,是否可以爲Get()
和Get([FromIDataUri] key)
返回不同的型號?是否可以在ODataController中返回不同的模型?
我喜歡使用ViewModels,當使用Get()
方法時,我想返回xxxOverviewViewModel
。當使用Get([FromIDataUri] key)
方法時,我想返回一個xxxViewModel。
這是可能的,如果是這樣,如何?
我試過返回不同的型號,但我總是得到406 Acceptable
。
Webapi.config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapODataServiceRoute("ODataRoute", "odata", GetEdmModel());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filter().Expand().Select().OrderBy().MaxTop(null).Count();
}
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<ComplaintViewModel>("ComplaintOData");
return builder.GetEdmModel();
}
}
ComplaintODataController
public class ComplaintODataController : ODataController
{
private readonly QueryProcessor _queryProcessor;
public ComplaintODataController(QueryProcessor queryProcessor)
{
_queryProcessor = queryProcessor;
}
[EnableQuery]
public IQueryable<ComplaintOverviewViewModel> Get()
{
var result = _queryProcessor.Handle(new GetAllComplaintsQuery());
return result;
}
// WHEN CALLING THIS METHOD I GET A 406:
[EnableQuery]
public ComplaintViewModel Get([FromODataUri] int key)
{
var result = _queryProcessor.Handle(new GetComplaintByIdQuery { Id = key });
return result;
}
}
編輯:
我GetAllComplaintsQuery.Handle
方法是這樣的:
public IQueryable<ComplaintOverviewViewModel> Handle(GetAllComplaintsQuery query)
{
// .All is an IQueryable<Complaint>
var result = _unitOfWork.Complaints.All.Select(c => new ComplaintOverviewViewModel
{
ComplaintType = c.ComplaintType.Description,
CreationDate = c.CreationDate,
Customer = c.Customer,
Description = c.Description,
Id = c.Id,
SequenceNumber = c.SequenceNumber,
Creator = c.Creator.Name
});
return result;
}
而且THI s是我ComplaintConfiguration
public class ComplaintConfiguration : EntityTypeConfiguration<Complaint>
{
public ComplaintConfiguration()
{
Property(p => p.SequenceNumber).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Property(p => p.Description).IsRequired();
}
}
你能分享代碼嗎? – Marusyk