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?
.ValueGeneratedOnAddOrUpdate()
. Attempt to generate migration gives "The property 'Id' cannot be configured as 'ValueGeneratedOnUpdate' or 'ValueGeneratedOnAddOrUpdate' because the key value cannot be changed after the entity has been added to the store." – Ivan Stoev Oct 9 '17 at 17:08OnModelCreating
override, renamedbuilder
tomodelBuilder
, removed.ValueGeneratedOnAddOrUpdate()
and everything works like a charm. – Ivan Stoev Oct 9 '17 at 19:38