简体   繁体   中英

Is it possible to use Entity Framework Core with existing database on tables with no primary key?

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"); } )

Another workaround is to create a temporary project with EF Core 3.0 and do the scaffolding, since it is possible to scaffold a database with no primary keys from this version on. Then you can copy the classes to your old project. You might need some minor changes but it will save a lot of work with big tables or if you have many tables without primary keys and you need to keep the EF Core version for the project.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM