我正在使用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中有什么变化吗?
答案 0 :(得分:0)
除了Ivan的答案之外,我猜你理解身份栏不需要ValueGeneratedOnAddOrUpdate。
您可以使用脚手架生成代码,在我的情况下,我使用CatFactory,您可以在此链接中查看它:https://www.codeproject.com/Articles/1160615/Generating-Code-for-EF-Core-with-CatFactory
此致