【问题标题】:The entity type requires a primary key to be defined in EF Core 2.0实体类型需要在 EF Core 2.0 中定义主键
【发布时间】:2017-10-10 13:05:52
【问题描述】:

我正在将带有 EF Core 的 ASP.NET Core 1.1 项目升级到 ASP.NET Core 2.0。

我有以下之前工作的实体和配置:

  public class Ebook {    
    public Int32 Id { get; set; }
    public String Title { get; set; }     
    public virtual ICollection<EbookFile> EbookFiles { get; set; } = new List<EbookFile>();    
  }

  public class EbookFile {        
    public Int32 EbookId { get; set; }
    public Int32 FileId { get; set; }    
    public virtual Ebook Ebook { get; set; }
    public virtual File File { get; set; }    
  }

  public class File {
    public Int32 Id { get; set; }
    public Byte[] Content { get; set; } 
    public virtual ICollection<EbookFile> EbookFiles { get; set; } = new List<EbookFile>();
  }

配置如下:

builder.Entity<Ebook>(b => {
  b.ToTable("Ebooks");
  b.HasKey(x => x.Id);
  b.Property(x => x.Id).ValueGeneratedOnAddOrUpdate().UseSqlServerIdentityColumn();
  b.Property(x => x.Title).IsRequired(true).HasMaxLength(200);
  b.HasIndex(x => x.Title).IsUnique();
});

builder.Entity<EbookFile>(b => {
  b.ToTable("EbookFiles");
  b.HasKey(x => new { x.EbookId, x.FileId });
  b.HasOne(x => x.Ebook).WithMany(x => x.EbookFiles).HasForeignKey(x => x.EbookId).IsRequired(true).OnDelete(DeleteBehavior.Cascade);
  b.HasOne(x => x.File).WithMany(x => x.EbookFiles).HasForeignKey(x => x.FileId).IsRequired(true).OnDelete(DeleteBehavior.Cascade);
});

builder.Entity<File>(b => {
  b.ToTable("Files");
  b.HasKey(x => x.Id);
  b.Property(x => x.Id).UseSqlServerIdentityColumn();
  b.Property(x => x.Content).IsRequired(false);
});

在我的 Context 类中,我有以下属性:

public DbSet<Ebook> Ebooks { get; set; }
public DbSet<EbookFile> EbookFiles { get; set; }
public DbSet<File> Files { get; set; }

当我运行它时,我得到了错误:

The entity type 'EbookFile' requires a primary key to be defined.

我在这里缺少什么? EF Core 2.0 有什么变化吗?

【问题讨论】:

  • 复合主键在我的项目中仍然可以正常工作,所以仅此而已。
  • 删除.ValueGeneratedOnAddOrUpdate()。尝试生成迁移会给出 “属性 'Id' 无法配置为 'ValueGeneratedOnUpdate' 或 'ValueGeneratedOnAddOrUpdate' 因为在实体添加到商店后无法更改键值。”
  • @Stoev 我删除了它,但我一直收到同样的错误......
  • 那么我能想到的就是通过在其上放置断点来检查显示的配置代码是否实际执行。因为我已经将它复制/粘贴到我的 EFC2.0 测试数据库上下文 OnModelCreating 覆盖,将 builder 重命名为 modelBuilder,删除了 .ValueGeneratedOnAddOrUpdate(),一切都像一个魅力。
  • @MiguelMoura 您介意解释一下“错误配置”是什么吗?

标签: c# entity-framework-core


【解决方案1】:

除了伊万的回答,我猜你明白身份列不需要 ValueGeneratedOnAddOrUpdate。

您可以使用脚手架生成代码,在我的情况下,我使用 CatFactory,您可以在此链接中查看它:https://www.codeproject.com/Articles/1160615/Generating-Code-for-EF-Core-with-CatFactory

问候

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 1970-01-01
    • 2021-07-23
    • 2021-11-27
    • 2018-08-13
    • 2019-09-13
    • 1970-01-01
    • 2022-11-19
    • 2017-11-23
    相关资源
    最近更新 更多