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()
static void Main(string[] args)
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<YourContext>());
//or
Database.SetInitializer(
new DropCreateDatabaseAlways<YourContext>());
//your code
}
Also i noticed you're using FluentAPI and i want to point you can also use attributes for mappings:
[Table("dfg_Product")]
public class Product
Hope it helps.
EDIT:
You are using
modelBuilder.Entity<Product>().ToTable("dfg_Product");
and this is why it created dbo.Product. Use
modelBuilder.Entity<Product>().MapSingleType().ToTable("dfg_Product");
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:
<add name="DataModelContainer" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With