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 cr
I had this issue with DBFirst and EF 6.1 it was creating a new table based on the EntityName. So I modified the OnModelCreating virtual method to map my tables.
So if the EntityName was named MyStuffs since by default the EnitityNames are pluralized which you do have the option to deselect that during the EF generation. In my case the wizard was generating the pluralized version of the table.
public class MyContext: DbContext
{
public MyContext()
: base("name=MyEntityConnectionName")
{
}
public MyContext(string connectionString)
: base(connectionString)
{
}
#region methods
public static MyContext Create()
{
return new MyContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Map Entities to their tables.
modelBuilder.Entity<MyModel>().ToTable("MyStuff"); //prevent a new table from being added since we added a mapping
}
#endregion
public virtual DbSet<MyModel> MyEntities{ get; set; }
}
Set the initialiser for your context to null
.
That should leave the database in it's existing state when the application starts up.
Note that you'll get an exception if you try to run the application after altering your dbContext class and/or your database schema, as your database schema will no longer match what the context expects.
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: