I am upgrading an ASP.NET Core 1.1 with EF Core project to ASP.NET Core 2.0.
I have the following entities and configurations which were working before:
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>();
}
And the configurations are:
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);
});
And on my Context class I have the properties:
public DbSet<Ebook> Ebooks { get; set; }
public DbSet<EbookFile> EbookFiles { get; set; }
public DbSet<File> Files { get; set; }
When I run it I get the error:
The entity type 'EbookFile' requires a primary key to be defined.
What am I missing here? Did something change in EF Core 2.0?
In Addition of Ivan's answer, I guess you understand identity column doesn't need ValueGeneratedOnAddOrUpdate.
You can generate code with scaffolding, in my case I use CatFactory you can check it in this link: https://www.codeproject.com/Articles/1160615/Generating-Code-for-EF-Core-with-CatFactory
Regards
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.