简体   繁体   中英

Prevent table generation for a specific entity in EF6

How do I disable table generation for a specific entity when my DB context is initialized?

public class MyDbContext : DbContext {
    public DbSet<MyEntity> MyEntity{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Ignore<MyEntity>();
        base.OnModelCreating(modelBuilder);
    }
}

This code helps but it excludes the entity completely and I still need to query it.

Without getting into too much detail, EF compares generated code your DB structure to the previous generated code when looking at migrations: it doesn't actually compare against the raw DB every time.

You should be able to bypass it wanting to create a table by creating a new migration, deleting/commenting out the table create code in UP and table remove code in DOWN, and apply the empty migration. It'll still have the view in the generated code, so it won't try to add it again.

You can create an empty migration as the first migration with the -IgnoreChanges flag to allow Entity Framework to get a snapshot of the existing database. For example:

Add-Migration InitialMigration -IgnoreChanges

This will map your entity to already existing table or a view in your case

modelBuilder.Entity<entityname>().ToTable("Tablename");

or using data annotations like this

[Table("tablename")] 
public class ClassName {
....
}

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