带有OData控制器的ASP.NET Core Web API需要对复合密钥使用流利的API

问题描述

我有一个现有的API,该数据库现在在其使用的数据库中具有表,这些表必须具有一个复合键。 我使用了流畅的API来定义dbcontext中的键。

protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
        //relationship modeling
        modelBuilder.Entity<Reports>().HasMany(r => r.Screenshots).WithOne().HasForeignKey(r => new { r.ReportId,r.itemTypeId });
        modelBuilder.Entity<Images>().HasOne(s => s.Reports).WithMany(s => s.Screenshots).HasForeignKey(s => new { s.ReportId,s.itemTypeId });
        modelBuilder.Entity<EpicReportsChildList>().HasOne(e => e.Reports).WithMany(e => e.EpicReports).HasForeignKey(e => new { e.TemplateId,e.parentTypeId });
        modelBuilder.Entity<Images>().HasOne(s => s.EpicReports).WithMany(s => s.Screenshots).HasForeignKey(s => new { s.ReportId,s.itemTypeId });

        
    }

我的启动文件包含以下内容

private IEdmModel GetEdmModel()
    {
        var oDatabuilder = new ODataConventionModelBuilder();
        oDatabuilder.EntitySet<Reports>("reports");

        return oDatabuilder.GetEdmModel();
    }

API返回以下错误

实体类EpicReportsChildList具有使用数据注释定义的复合主键。要设置复合主键,请使用fluent API。

解决方法

实体类型EpicReportsChildList已定义复合主键 带有数据注释。要设置复合主键,请使用fluent API。

如错误消息所述,也许您正在使用数据注释或流畅的API方法配置复合主键。

EF Core Keys document中,我们发现:只能使用Fluent API配置复合键;只能使用Fluent API进行配置。约定永远不会设置组合键,并且您不能使用“数据注释”来配置组合键。

因此,请检查相关模型并尝试删除数据注释:[Key]属性或[ForeignKey]修饰符。

有关使用组合键配置关系的更多详细信息,可以查看以下文章(将多对多关系联接表配置为使用组合主键,您可以参考它们):

EF one to many on part of composite primary key

Configure Many-to-Many Relationships in Entity Framework Core

Configuring Many To Many Relationships in Entity Framework Core