OData webapi2无法将Account更改为AccountViewModel

时间:2014-07-23 04:41:24

标签: asp.net-web-api odata

我有以下

        [EnableQuery]
        public IQueryable<AccountViewModel> GetAccounts()
        {
            return _accountRepository.Table
                .Select(x => new Bepoz.Api.Models.AccountViewModel() {Title = x.Title, AccountID = x.AccountID}).AsQueryable();
        }

    [EnableQuery]
    public SingleResult<AccountViewModel> GetAccount([FromODataUri] int key)
    {
        return SingleResult.Create(this._accountRepository.Table.Where(account => account.AccountID == key)
            .Select(x => new Bepoz.Api.Models.AccountViewModel() { Title = x.Title, AccountID = x.AccountID }).AsQueryable());
    }

在我的WebApiConfig

        public static void Register(HttpConfiguration config)
        {
            // New code:
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<AccountViewModel>("Accounts");
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: "odata",
                model: builder.GetEdmModel());
        }

执行时

http://localhost:55045/odata/Accounts

响应是所有帐户的预期,但是当我执行

http://localhost:55045/odata/Accounts(1)

我得到了

{
  "error":{
    "code":"","message":"No HTTP resource was found that matches the request URI 'http://localhost:55045/odata/Accounts(1)'.","innererror":{
      "message":"No routing convention was found to select an action for the OData path with template '~/entityset/key'.","type":"","stacktrace":""
    }
  }
}

我的AccountViewModel看起来像这样

public class AccountViewModel
{
    [Key]
    public int AccountID { get; set; }
    public string Title { get; set; }
}

仅供参考 - 如果我将类从AccountViewModel更改为Account,它将起作用! 感谢

1 个答案:

答案 0 :(得分:1)

您唯一需要做的就是再添加两行:

ODataModelBuilder builder = new ODataConventionModelBuilder();
EntitySetConfiguration<AccountViewModel> accounts= builder.EntitySet<AccountViewModel>("Accounts");
EntityTypeConfiguration<AccountViewModel> account = accounts.EntityType;
account.Name = "Account";