DbContext Table mappings

本文关键字:mappings Table DbContext | 更新日期: 2023-09-27 18:26:30

我已经尝试过实现这个场景。我创建了代码优先模型,然后从模型中生成数据库sql,并通过MigSharp创建了手动迁移。之后,我将代码添加到OnModelCreating以更新映射。

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

问题是DbContext仍然试图从默认映射"dbo.Product|dbo.Customer"中获取数据,我需要将映射更改为"dbo.dfg_Product|dbo.dfg_Customer"。我尝试过调试,但OnModelCreating中的代码没有被调用。

请帮帮我,我做错了什么?

编辑:添加了连接字符串

<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" />

通过将连接字符串更改为:解决了问题

<add name="DataModelContainer" connectionString="Data Source=localhost'SQLEXPRESS;Initial Catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

DbContext Table mappings

如果您以前执行过应用程序,并且您的模型保持不变,则数据库已经存在,并且不会调用OnModelCreating()

您可以使用Database.SetInitializer()

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

此外,我注意到您正在使用FluentAPI,我想指出的是,您也可以使用属性进行映射:

[Table("dfg_Product")]
public class Product

希望能有所帮助。

编辑:

您正在使用

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

这就是它创建dbo的原因。产品使用

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

并且请使用DropCreateDatabaseAlways(),这样您将获得具有正确映射的新数据库。

编辑2

在开发代码优先应用程序时,您不需要连接字符串中的元数据信息,因此您的连接字符串应该如下所示:

<add name="DataModelContainer" connectionString="Data Source=localhost'SQLEXPRESS;Initial Catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />