Han*_*anu 6 c# entity-framework odata asp.net-web-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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
woe*_*liJ 15
您为实体框架的数据库映射定义了密钥,但没有为OData映射定义密钥.
试试这个:
private static IEdmModel GetEDMModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
var entitySet = builder.EntitySet<TestEntity>("TestEntities");
entitySet.EntityType.HasKey(entity => entity.EntityID)
return builder.GetEdmModel();
}
Run Code Online (Sandbox Code Playgroud)
或者尝试向[Key]
TestEntity 添加一个属性,以告诉OData(和实体框架同时)什么属性是关键.
像这样:
using System.ComponentModel.DataAnnotations;
public class TestEntity
{
[Key]
public int EntityID { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我来自谷歌,遇到了这个错误,这是我班上课的一个例子
public class TestEntity
{
[Key]
public int EntityID { get; }//<-- missing set
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
只有将集合添加到[key]属性后,它才能解析。这是最终结果
public class TestEntity
{
[Key]
public int EntityID { get; set; }//<--- added set
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)