Prevent table generation for a specific entity in EF6

.net c# ef-migrations entity-framework entity-framework-6

Question

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.

1
1
6/21/2016 11:58:09 AM

Accepted Answer

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.

2
6/21/2016 12:36:38 PM

Popular Answer

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 {
....
}


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