gpt4 book ai didi

c# - 实体类型需要在 EF Core 2.0 中定义主键

转载 作者:行者123 更新时间:2023-11-30 18:16:24 25 4
gpt4 key购买 nike

我正在将带有 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 有什么变化吗?

最佳答案

除 Ivan 的回答外,我想您了解标识列不需要 ValueGeneratedOnAddOrUpdate。

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

问候

关于c# - 实体类型需要在 EF Core 2.0 中定义主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46650529/

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