简体   繁体   English

阻止在EF6中为特定实体生成表

[英]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. 无需过多讨论,EF在查看迁移时会将数据库结构的生成代码与先前生成的代码进行比较:实际上,它并非每次都与原始DB进行比较。

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. 您应该能够通过创建新迁移,在UP中删除/注释表创建代码和在DOWN中删除表注释代码,并应用空迁移来绕过想要创建表的想法。 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. 您可以使用-IgnoreChanges标志创建一个空迁移作为第一次迁移,以允许Entity Framework获取现有数据库的快照。 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 {
....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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