我已将数据库中的视图导入到edmx,并将[Key]属性添加到模型POCO类中:
名称空间TFOMS.Domain.Model
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class vw_Tariffs_PR
{
public int TariffId { get; set; }
public string MCOD { get; set; }
public string OrgName { get; set; }
public Nullable<int> IDPR { get; set; }
public string PRNAME { get; set; }
public Nullable<int> IDSP { get; set; }
public string SPNAME { get; set; }
public Nullable<byte> isChild { get; set; }
public decimal tariff { get; set; }
public System.DateTime DATEBEG { get; set; }
public Nullable<System.DateTime> DATEEND { get; set; }
}
}
我需要在webapi odata控制器中公开这个视图,但是当我向WebApiConfig.cs添加以下代码时
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<vw_Tariffs_PR>("vw_Tariffs_PR");
var model = builder.GetEdmModel();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: model);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
但是当我启动应用程序时,我收到错误: {&#34;实体&#39; vw_Tariffs_PR&#39;没有定义键。&#34;} 在 var model = builder.GetEdmModel();
将[Key]属性添加到TariffId属性后,我收到错误:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Код, выполняемый при запуске приложения
AreaRegistration.RegisterAllAreas();
**GlobalConfiguration.Configure(WebApiConfig.Register);**
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
在线GlobalConfiguration.Configure(WebApiConfig.Register); {&#34; ValueFactory尝试访问此实例的属性值。&#34;}
任何人都可以解释如何在odata控制器中公开视图,我做错了什么?
答案 0 :(得分:1)
问题在于WebApiConfig.cs中的路由序列,odata路由必须在webapi路由之后:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API configuration and services
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<vw_Tariffs_PR>("vw_Tariffs_PR");
var model = builder.GetEdmModel();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: model);
}
}