I'm trying to use Entity Framework Core with an existing database. This database has several tables that don't have primary keys set due to other processes (out side of the scope of the application I'm building) that will break if the primary key is set.
Is it possible to create models of tables without the primary key?
I'm currently using:
- Microsoft.EntityFrameworkCore -Version 2.0.1
- Microsoft.EntityFrameworkCore.SqlServer -Version 2.0.1
- Microsoft.EntityFrameworkCore.SqlServer.Design -Version
- Microsoft.EntityFrameworkCore.Tools -Version 2.0.1
- Microsoft.EntityFrameworkCore.Tools.DotNet -Version 2.0.0
I get this error when running the command below "Unable to generate entity type for table '...'. Please see the warning messages."
Command that I'm running:
Scaffold-DbContext "Server=...myservernamehere...;Database=...mydbnamehere...;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Scafford will not work without a Primary Key. However, there is a workaround. At least in 2.2.0, I can't say for sure if this will work in older versions.
After you Scaffold the DBContext file for the database
At least one of your columns has to be unique data
You will need to create a model class for the table with all the columns you care about. It would be best to use the same name and data type as the table.
Create your DbSet
public virtual DbSet<Model of table> { get; set; }
In your OnModelCreating(ModelBuilder modelBuilder)
create the mapping to the table
modelBuilder.Entity<Model of table>(entity =>
{
entity.HasKey(e => e.{Unique column});
entity.ToTable("Table's Name");
}
)