Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

.net - How to prevent DbContext from altering the database?

I'm learning Entity Framework (currently using EF6 beta) and I'm using the code first pattern on an existing database. The entities and DbContext class are created automatically using a T4 template.

I would like to prevent the DbContext from creating / altering anything into the database at runtime.

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do enable-migrations command, you will be presented with folder /Migrations under which you can find file named Configuration.cs. Within constructor of that file, by the default, there is a property set to value:

 AutomaticMigrationsEnabled = false;

Which will ensure that your database won't be migrated automatically, but rather by invoking each migration manually.

However, if your database is larger than your domain models, i.e. you're just operating on the portion of already existing database, then somewhere in your application start (if it is ASP.NET app, Application_Start event handler), you need to add the following code:

Database.SetInitializer<YourDbContext>(null);

Otherwise, Entity Framework will complain that there is a mismatch between database definition in your domain model and actual current state of the database.

EDIT:

If you want to be sure that YourDbContext is not attempting to change database, do this:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    throw new YourCustomException("Code first changes are not allowed."); 
}

EDIT again:

I'm trying to understand what scenario are you trying to accomplish. If you have existing database, and you want to update it but only manually, this is the approach:

  1. Use DbContext generator template to generate DbContext and entities from existing database.
  2. Run enable-migrations
  3. Do add-migration Initial
  4. Step 3 should generate empty migration if everything was done properly. You can delete it.
  5. Now whenever you do some change, you need to do add-migration ChangeName. This will not go to database, unless you do update-database.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...