gpt4 book ai didi

c# - DbContext 表映射

转载 作者:行者123 更新时间:2023-11-30 15:05:01 25 4
gpt4 key购买 nike

我已经尝试实现这个 scenario .我创建了 Code First 模型,然后从模型生成数据库 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" />

最佳答案

如果您之前执行过您的应用程序并且您的模型保持不变,则数据库已经存在并且不会调用 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.Product 的原因。使用

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

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

编辑 2

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

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

关于c# - DbContext 表映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9549828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com