The entity type requires a primary key to be defined in EF Core 2.0

c# entity-framework-core

Question

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?

1
3
10/9/2017 4:01:21 PM

Popular Answer

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

0
10/10/2017 5:05:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow