DbContext table mapping

I tried to implement this scenario . I created the Code First model, then generated a sql database from the model and created manual migration through MigSharp . After that, I added code to OnModelCreating to update the mappings.

 protected void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Product>().ToTable("dfg_Product"); modelBuilder.Entity<Customer>().ToTable("dfg_Customer"); } 

The problem is that DbContext is still trying to get data from the default mappings of "dbo.Product | dbo.Customer", and I need to change the mappings to "dbo.dfg_Product | dbo.dfg_Customer". I tried to debug, but the code in OnModelCreating not called.

Please help, what am I 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=&quot;data source=localhost\SQLEXPRESS;initial catalog=TestDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 

The problem was resolved by changing the connection string:

 <add name="DataModelContainer" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" /> 
+4
source share
1 answer

If you executed your application earlier and your model remains the same, the database already exists and OnModelCreating() will not be called.

You can use Database.SetInitializer()

 static void Main(string[] args) { Database.SetInitializer( new DropCreateDatabaseIfModelChanges<YourContext>()); //or Database.SetInitializer( new DropCreateDatabaseAlways<YourContext>()); //your code } 

I also noticed that you are using FluentAPI, and I want to indicate that you can also use attributes for mappings:

 [Table("dfg_Product")] public class Product 

Hope this helps.

EDIT:

You are using

 modelBuilder.Entity<Product>().ToTable("dfg_Product"); 

and that is why he created dbo.Product. Use

 modelBuilder.Entity<Product>().MapSingleType().ToTable("dfg_Product"); 

and use DropCreateDatabaseAlways() to get the new database with the correct mappings.

EDIT 2

You do not need metadata information in the connection string when developing the 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" /> 
+5
source

Source: https://habr.com/ru/post/1399579/


All Articles