gpt4 book ai didi

ef-code-first - 如何在 Entity Framework 4.3 Code First 中禁用 __MigrationHistory 表?

转载 作者:行者123 更新时间:2023-12-04 02:10:21 31 4
gpt4 key购买 nike

我使用 Entity Framework 4.3 Code First 和这样的自定义数据库初始值设定项:

public class MyContext : DbContext
{
public MyContext()
{
Database.SetInitializer(new MyContextInitializer());
}
}

public class MyContextInitializer : CreateDatabaseIfNotExists<MyContext>
{
protected override void Seed(MyContext context)
{
// Add defaults to certain tables in the database

base.Seed(context);
}
}

每当我的模型发生变化时,我都会手动编辑我的 POCO 和映射,并手动更新我的数据库。

当我再次运行我的应用程序时,我收到此错误:

Server Error in '/' Application.

The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).



使用 EFProfiler,我还注意到这些查询正在执行:
-- statement #1
SELECT [GroupBy1].[A1] AS [C1]
FROM (SELECT COUNT(1) AS [A1]
FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [GroupBy1]

-- statement #2
SELECT TOP (1) [Project1].[C1] AS [C1],
[Project1].[MigrationId] AS [MigrationId],
[Project1].[Model] AS [Model]
FROM (SELECT [Extent1].[MigrationId] AS [MigrationId],
[Extent1].[CreatedOn] AS [CreatedOn],
[Extent1].[Model] AS [Model],
1 AS [C1]
FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [Project1]
ORDER BY [Project1].[CreatedOn] DESC

我怎样才能防止这种情况?

最佳答案

起初我确定这是因为您在 ctor 中设置了默认初始值设定项,但稍微调查了一下我发现初始值设定项在创建上下文时不会运行,而是在您第一次查询/添加某些内容时运行。

提供的初始值设定项都检查模型兼容性,因此您对它们不走运。不过,您可以轻松地像这样制作自己的初始化程序:

 public class Initializer : IDatabaseInitializer<Context>
{

public void InitializeDatabase(Context context)
{
if (!context.Database.Exists())
{
context.Database.Create();
Seed(context);
context.SaveChanges();
}
}

private void Seed(Context context)
{
throw new NotImplementedException();
}
}

这不应该检查兼容性,如果数据库丢失,它将创建它。

更新:“上下文”应该是你的 DbContext 实现的类型

关于ef-code-first - 如何在 Entity Framework 4.3 Code First 中禁用 __MigrationHistory 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11259079/

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