gpt4 book ai didi

c# - Web APi OData V4 问题 "The entity ' ' 没有定义键

转载 作者:太空狗 更新时间:2023-10-29 20:49:09 24 4
gpt4 key购买 nike

当我运行以下示例时,它抛出以下异常...

Additional information: The entity 'TestEntity' does not have a key defined.

我已经使用代码优先实体上下文配置了 key ... modelBuilder.Entity<TestEntity>().HasKey(t => t.EntityID);

问题是什么?为什么 OData V4 没有使用配置的 key ?

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);

}
}

}

最佳答案

您为 Entity Framework 的数据库映射定义了键,但没有为 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(同时还有 Entity Framework)什么属性是键。

像这样:

using System.ComponentModel.DataAnnotations;

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

关于c# - Web APi OData V4 问题 "The entity ' ' 没有定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com