I have tried to implement this scenario. I have created Code First model, then generated database sql from model, and have created manual migrations via MigSharp. After that i have added code to OnModelCreating to update mappings.
protected void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("dfg_Product");
modelBuilder.Entity<Customer>().ToTable("dfg_Customer");
}
Problem is that DbContext still trying to get data from default mappings “dbo.Product | dbo.Customer” and I need to change mappings to “dbo.dfg_Product | dbo.dfg_Customer”.
I have tried to debug but code in OnModelCreating does not invoked.
Please help, what I am doing wrong?
EDIT: Added connection string
<add name="DataModelContainer" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=TestDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Problem was solved by changing connection string to:
<add name="DataModelContainer" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
If you executed your application before and your model remains the same, the database is already there and
OnModelCreating()will not get called.You can use
Database.SetInitializer()Also i noticed you’re using FluentAPI and i want to point you can also use attributes for mappings:
Hope it helps.
EDIT:
You are using
and this is why it created dbo.Product.
Use
and please use
DropCreateDatabaseAlways()so you’ll get a new database with correct mappings.EDIT 2
You don’t need metadata information in the connection string when developing a Code First application so your connection string should look like this: