C# EF5 收到此错误消息:无法检查模型兼容性,因为数据库不包含模型元数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14064434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:35:16  来源:igfitidea点击:

EF5 Getting this error message: Model compatibility cannot be checked because the database does not contain model metadata

c#.netentity-frameworkentity-framework-5

提问by Pedigree

I have this error message that keeps on displaying every time I run the application. I'm using Entity Framework 5: Code First

我每次运行应用程序时都会显示此错误消息。我正在使用实体Framework 5: Code First

Here's the error message,

这是错误信息,

System.NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
   at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
   at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
   at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)
   at System.Data.Entity.DropCreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context)
   at System.Data.Entity.Database.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)
   at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at LaundryService_DEMO.frmMain.btnCreate_Click(Object sender, EventArgs e) in d:\MyDocs\Visual Studio 2012\Projects\LaundryService_DEMO\LaundryService_DEMO\frmMain.cs:line 39

This error started when I created an entity called invoice. Here's the full code of the entity,

当我创建一个名为 invoice 的实体时,这个错误就开始了。这是实体的完整代码,

public class Invoice
{
    public string InvoiceID { get; set; }
    public string CustomerID { get; set; }
    public string UserID { get; set; }
    public decimal TotalAmount { get; set; }
    public DateTime TransactionDate { get; set; }
    public DateTime PaymentDate { get; set; }

    public Customer CustomerField { get; set; }
    public SystemUser SystemUserField { get; set; }
}

public class InvoiceMap : EntityTypeConfiguration<Invoice>
{
    public InvoiceMap()
    {
        // Primary Key
        this.HasKey(x => x.InvoiceID);

        // Property(ies) and Mapping(s)
        this.ToTable("Invoice");

        this.Property(x => x.InvoiceID)
            .IsRequired()
            .HasMaxLength(15)
            .HasColumnName("InvoiceID")
            .HasColumnType("nVarchar");

        this.Property(x => x.CustomerID)
            .IsRequired()
            .HasMaxLength(15)
            .HasColumnName("CustomerID")
            .HasColumnType("nVarchar");

        this.Property(x => x.UserID)
            .IsRequired()
            .HasMaxLength(15)
            .HasColumnName("UserID")
            .HasColumnType("nVarchar");

        this.Property(x => x.TotalAmount)
            .IsRequired()
            .HasColumnName("TotalAmount")
            .HasColumnType("decimal");

        this.Property(x => x.TransactionDate)
            .IsRequired()
            .HasColumnName("TransactionDate")
            .HasColumnType("datetime");

        this.Property(x => x.PaymentDate)
            .IsOptional()
            .HasColumnName("PaymentDate")
            .HasColumnType("datetime");

        // Relationship
        this.HasRequired(x => x.CustomerField)
            .WithMany(x => x.InvoiceCollection)
            .HasForeignKey(y => y.CustomerID);

        this.HasRequired(x => x.SystemUserField)
            .WithMany(x => x.InvoiceCollection)
            .HasForeignKey(y => y.UserID);
    }
}

In order to replicate the application, I have included the project file which is available for download. And so this question will not be full of code.

为了复制该应用程序,我包含了可供下载的项目文件。所以这个问题不会充满代码。

If there are details that I've missed in the question, please comment so I can include it.

如果我在问题中遗漏了细节,请发表评论,以便我可以将其包含在内。

采纳答案by Pedigree

I found the code working by changing

我发现代码通过更改工作

static LaundryShopContext()
{
  Database.SetInitializer<LaundryShopContext>(
    new DropCreateDatabaseIfModelChanges<LaundryShopContext>());
}

into

进入

static LaundryShopContext()
{
  Database.SetInitializer<LaundryShopContext>(
    new DropCreateDatabaseAlways<LaundryShopContext>());
}

回答by Judo

This is probably related to your database not containing the _MigrationHistory table (which can be viewed using SQL Server Management Studio in Tables > System Tables).

这可能与您的数据库不包含 _MigrationHistory 表(可以使用 SQL Server Management Studio 在表 > 系统表中查看)有关。

Not sure how you are managing the database, but if you are still in development and using EF Migrations a quick solution is to delete the database and run Update-Database which will recreate the entire database and add the _MigrationHistory table.

不确定您是如何管理数据库的,但如果您仍在开发并使用 EF 迁移,一个快速的解决方案是删除数据库并运行 Update-Database,这将重新创建整个数据库并添加 _MigrationHistory 表。

If you want to avoid EF running this check you can add this to your DbContext class

如果您想避免 EF 运行此检查,您可以将其添加到您的 DbContext 类

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}

回答by Stark

This can also happen if you are trying to initialise the context against a previously existing database of the same name but that was created with another codebase. This is why changing from DropCreateDatabaseIfModelChanges to DropCreateDatabaseAlways works, the latter configuration causes the database to be recreated no matter what, bypassing any sort of database versioning that might be causing this issue.

如果您尝试针对先前存在的同名数据库初始化上下文,但该数据库是使用另一个代码库创建的,也会发生这种情况。这就是为什么从 DropCreateDatabaseIfModelChanges 更改为 DropCreateDatabaseAlways 的原因,后一种配置无论如何都会导致重新创建数据库,绕过可能导致此问题的任何类型的数据库版本控制。

回答by Ahsanul

CreateDatabaseIfNotExists<ApplicationDbContext>();

回答by Jason Conville

If, like me, this is caused by starting with Code First and changing to Database First development mid-project.. this is all caused by one simple line. If you need to keep your database and its data comment out the following line:

如果像我一样,这是由于从 Code First 开始并在项目中期更改为 Database First 开发造成的。这都是由一条简单的线引起的。如果您需要保留数据库及其数据,请注释掉以下行:

Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());

from this section of your Model.

从模型的这一部分。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
    static ApplicationDbContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        //   Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

This will happen often in when starting out with the built in identity models. Once you get them working, you can remove that line to keep it intact yet retain the functionality. If your model changes, however, your database will have to be configured to match.. something you are doing in Database First development anyway!

在开始使用内置身份模型时,这种情况经常发生。一旦你让它们工作,你可以删除那条线以保持它的完整性并保留功能。但是,如果您的模型发生变化,您的数据库将必须配置为匹配……无论如何您在数据库优先开发中所做的事情!

回答by Richard D

I got this error when I add
ContextKey = "MyProject.Repository.Common.DbContextA";

添加时出现此错误
ContextKey = "MyProject.Repository.Common.DbContextA";

to Configuration.cs. After remove that line, it works.

到 Configuration.cs。删除该行后,它可以工作。

回答by Satheesh K

I tried below 3 steps . It works for me.. Run the following commands in package manager console 1. enable-migrations 2. update-database -verbose 3. add-migration initialmigrations -ignorechanges

我尝试了以下 3 个步骤。它对我有用.. 在包管理器控制台中运行以下命令 1. enable-migrations 2. update-database -verbose 3. add-migration initialmigrations -ignorechanges

NOTE: My scenario is I already created the db/tables (using code first approach (using a shared DB context library). I trying to use the library in another application and another database. I manually synched the first db into second.. thats why i encountered this problem.

注意:我的场景是我已经创建了 db/tables(使用代码优先方法(使用共享数据库上下文库)。我尝试在另一个应用程序和另一个数据库中使用该库。我手动将第一个 db 同步到第二个 ..为什么我遇到这个问题。

回答by Jens Ehrich

I know I'm late to the party, but I just came across the same error, and my database already had a migration history table.

我知道我迟到了,但我刚刚遇到了同样的错误,而且我的数据库已经有一个迁移历史表。

The error might also indicate an incorrect context key in the history table. This may happen if you move the database context class to another namespace, like I did while refactoring.

该错误还可能表示历史表中的上下文键不正确。如果您将数据库上下文类移动到另一个命名空间,就可能发生这种情况,就像我在重构时所做的那样。

Updating the ContextKeyvalue in the MigrationHistorytable to the new namespace of the database context fixed the issue for me.

ContextKeyMigrationHistory表中的值更新为数据库上下文的新命名空间为我解决了这个问题

This solution does not require you to discard the database contents so may be preferred over the DropCreateDatabaseAlwayssolution.

此解决方案不需要您丢弃数据库内容,因此可能优于该DropCreateDatabaseAlways解决方案。