c# - EF Code First from Database - 已经是数据库中的一个对象

标签 c# entity-framework entity-framework-6

我创建了一个新的 .NET 项目并添加了 ADO.NET EF 6。
我完成了 EF 向导并从数据库中选择代码优先。
然后我选择了一张 table 。我们称它为“产品”。
这创建了“公共(public)部分类 Product”和“公共(public)部分类 Model1”。

我立即在我的应用程序中创建了一个 LINQ 查询来查询“产品”,但我收到以下错误。

There is already an object named 'Product' in the database.

当我运行 SQL Profile 时,我看到以下内容:

CREATE TABLE [dbo].[Product] ...

我不明白为什么该项目要尝试创建该表,因为该表已经存在。

我读了几篇文章告诉我需要启用迁移,但我真的不希望我的项目能够在数据库中创建表。
(我们有一个 DBA 不允许我们在数据库中“轻松”创建表)

然后我决定尝试使用以下内容创建“迁移”文件夹和“内部密封类配置”:

public Configuration()
{
    AutomaticMigrationsEnabled = false;
    AutomaticMigrationDataLossAllowed = false;
}

这给了我一个新的错误。

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

我该如何解决这个问题?

更新
所以我创建了一个 VB.NET 和一个 C# 应用程序,它们使用完全相同的代码指向同一个数据库。
C#版本存在“已经在数据库中”的问题。
VB.NET版本没有“已经在数据库中”的问题。

最佳答案

我不确定为什么,但在 VB.NET 中,数据库中的代码优先工作正常,但在 C# 中,这对于 EF6 无法正常工作。

我决定让 C# 创建“dbo.__MigrationHistory”,并发现这很有效,直到我添加了一个与数据库中的表同名的新类。
这导致了以下错误:

The model backing the 'TEST' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.

我再次想到为什么当我已经有一个数据库并尝试使用 Code First“FROM”数据库时 EF 需要迁移信息。

因此,通过快速搜索 StackOverFlow,我找到了以下文章:
Entity Framework Code Only error: the model backing the context has changed since the database was created
在 Global.asax 中添加以下代码行后,一切都开始正常工作。

Database.SetInitializer<YourContext>(null);

关于c# - EF Code First from Database - 已经是数据库中的一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33661070/

相关文章:

entity-framework - EF4 CTP5 的存储库模式

c# - 从 IdentityUser 继承我在 UserManager<User> 上收到错误

c# - Entity Framework 4.1、Generic Repository 和 ObservableCollection

c# - 如何将现有实体附加到通用的 Entity Framework 上下文?

C# Regex.replace 需要模式

c# - 属性更改时在ViewModel中执行方法

c# - 下拉选择 future 10 年的列表

c# - 什么是NullReferenceException,如何解决?

c# - 奇怪的 Linq to Entities 行为与 AsExpandable()

entity-framework-6 - Entity Framework 种子方法异常