Web APi OData V4问题“实体''没有定义密钥

时间:2017-06-05 14:34:12

标签: c# entity-framework asp.net-web-api odata 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);

        }
    }

}

3 个答案:

答案 0 :(得分:13)

您为实体框架的数据库映射定义了密钥,但没有为OData映射定义密钥。

试试这个:

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

或尝试向TestEntity添加[Key]属性,以告知OData(和实体框架同时)什么属性是关键。

像这样:

using System.ComponentModel.DataAnnotations;

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

答案 1 :(得分:4)

我是从谷歌来到这里并遇到了这个错误,这是我班级看起来像

的一个例子
public class TestEntity
{
    [Key]
    public int EntityID { get; }//<-- missing set
    public string Name { get; set; }
}

只有在我将设置添加到我的[key]属性后才能解决。这是最终结果

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

答案 2 :(得分:1)

如果类名是TestEntity且id字段是EntityID,则问题是将类名更改为Entity或将字段名更改为Id或TestEntityId这对我有用,您可以检查this link以获取更多解决方案事实并非如此。