且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

停止实体框架修改数据库

更新时间:2023-02-02 12:15:07

如果您不希望EF创建数据库,可以禁用数据库初始化程序:

  public class SchoolDBContext:DbContext 
{
public Sc​​hoolDBContext():base(SchoolDBConnectionString)
{
//禁用初始化器
Database.SetInitializer&SchoolDBContext&gt );
}
public DbSet< Student>学生{get;组; }
public DbSet< Standard>标准{get;组; }
}

请参阅 http://www.entityframeworktutorial.net/code-first/turn-off-database-initialization-in -code-first.aspx


I'm starting to play around with the code-first approach to the entity framework, primarily so that I can decorate my properties with annotations for display in my view (otherwise, right now I have to create a class that is nearly identical to the one that entity framework generated for me just so I can add annotations, and then copy the data from one object to the next).

Right now it looks like when I start my application it is trying to create a database.

I do not want entity framework to ever modify my database. No. Not ever. Don't even try it. It really isn't that hard to modify databases; I would feel much more comfortable if I did that myself. I don't need a framework to hold my hand when designing a database.

Can I tell the framework to stop trying to modify my database? I'm very hesitant to use code-first now as the fact that it's trying to modify my database is rather frightening. Even in development I never want to see it happen.

Am I out of luck?

If you don't want EF to create your database, you can disable the database initializer:

public class SchoolDBContext: DbContext 
{
    public SchoolDBContext() : base("SchoolDBConnectionString")
    {            
        //Disable initializer
        Database.SetInitializer<SchoolDBContext>(null);
    }
    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
}

See http://www.entityframeworktutorial.net/code-first/turn-off-database-initialization-in-code-first.aspx