2017-06-05 57 views
1

當我運行下面的示例它拋出以下異常...網頁API的OData V4頒發的」實體‘’沒有一個鍵定義

附加信息:實體‘TestEntity’不有定義的鍵。

我已經配置使用代碼第一個實體方面的關鍵... modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

問題是什麼?爲什麼OData的V4不使用配置的密鑰?

namespace WebApplication2 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

      config.MapODataServiceRoute("odata", "odata", model: GetEDMModel()); 

     } 

     private static IEdmModel GetEDMModel() 
     { 
      ODataModelBuilder builder = new ODataConventionModelBuilder(); 
      builder.EntitySet<TestEntity>("TestEntities");    
      return builder.GetEdmModel(); 
     } 
    } 


    public class TestEntity 
    { 
     public int EntityID { get; set; } 
     public string Name { get; set; } 
    } 

    public partial class TestContext1 : DbContext 
    { 

     public TestContext1() : base("DB") 
     { 
     } 
     public DbSet<TestEntity> Entities { get; set; }   
     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID); 

     } 
    } 

} 

回答

2

您爲實體框架的數據庫映射定義了密鑰,但是沒有爲OData映射定義密鑰。

試試這個:

private static IEdmModel GetEDMModel() 
{ 
     ODataModelBuilder builder = new ODataConventionModelBuilder(); 
     var entitySet = builder.EntitySet<TestEntity>("TestEntities"); 
     entitySet.EntityType.HasKey(entity => entity.EntityID) 
     return builder.GetEdmModel(); 
} 

或嘗試加入[Key]屬性您TestEntity告訴OData的(和Entity Framework在同一時間)什麼屬性是關鍵。

像這樣:

using System.ComponentModel.DataAnnotations; 

public class TestEntity 
{ 
    [Key] 
    public int EntityID { get; set; } 
    public string Name { get; set; } 
} 
+0

在代碼第一個上下文已經映射/配置的密鑰。爲什麼我們必須再配置一次。此外,相同的代碼適用於OData v3版本「Microsoft.AspNet.WebApi.OData」,但這不適用於「Microsoft.AspNet.OData」 – Hanu

+0

您配置的是用於實體框架映射。可能OData需要不同的映射。您可能還可以通過在EntityID屬性 – woelliJ

+0

modelBuilder.Entity ().HasKey(t => t.EntityID)上添加一個'[Key]'屬性來繞開這個問題。但爲什麼它使用[Key]屬性。此外,這是以前版本中的支持功能。 – Hanu

0

如果類名是TestEntity和ID字段ENTITYID這就是問題更改類名稱的實體或字段名Id或TestEntityId這個工作對我來說,你如果不是這種情況,可以檢查this link獲取更多解決方案。

1

我來到這裏,從谷歌,跑進這個錯誤,這裏是一個什麼我的課看起來像

public class TestEntity 
{ 
    [Key] 
    public int EntityID { get; }//<-- missing set 
    public string Name { get; set; } 
} 

後,才加入設置我的[關鍵]屬性沒有得到它解決的例子。這裏是最終結果

public class TestEntity 
{ 
    [Key] 
    public int EntityID { get; set; }//<--- added set 
    public string Name { get; set; } 
} 
相關問題