asp.net-mvc 使用 EF 6 和 MVC 5 中的代码优先方法将新表添加到现有数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27958793/
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-09-07 23:22:23  来源:igfitidea点击:

Add new table to an existing database using Code First approach in EF 6 and MVC 5

asp.net-mvcentity-frameworkasp.net-mvc-5ef-migrations

提问by nemo_87

I know this should be simple, but I was unable to find correct tutorial or explanation on web on this subject. There is a lot of videos and posts about adding new column to an existing table, using code first approach, but I can not find any with step by step explanation on how to add whole new table into existing database. Which is weird, I was pretty sure that I will find many examples. Maybe my search criteria is bad. So if anybody has any good link or video, please share.

我知道这应该很简单,但是我无法在网上找到有关此主题的正确教程或解释。有很多关于使用代码优先方法向现有表添加新列的视频和帖子,但我找不到任何关于如何将整个新表添加到现有数据库的分步说明。这很奇怪,我很确定我会找到很多例子。也许我的搜索条件不好。所以如果有人有任何好的链接或视频,请分享。

What I'm trying to do is to add table Post into existing Default Database, created by MVC 5 project. I've made model class first, named it Post and it has a simple definition:

我想要做的是将表 Post 添加到由 MVC 5 项目创建的现有默认数据库中。我首先创建了模型类,将其命名为 Post,它有一个简单的定义:

public class Post
    {
        [Key]
        public int PostId { get; set; }
        public string PostText { get; set; }
        public byte[] ImagePost { get; set; }
        public byte[] FilePost { get; set; }
        public string TextPost { get; set; }
        public string UserId { get; set; }
    } 

Then I have first doubts. I know I should create DbContext, but if I want to hit an existing database, should I use existing DbContext, already created by default in Web.config file like this:

那么我首先有疑问。我知道我应该创建 DbContext,但是如果我想访问现有的数据库,我应该使用现有的 DbContext,它已经在 Web.config 文件中默认创建,如下所示:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-StudentBookApp-20150114035149.mdf;Initial Catalog=aspnet-StudentBookApp-20150114035149;Integrated Security=True"
      providerName="System.Data.SqlClient" />

Or I should use all new DbContext created for Post class?

或者我应该使用为 Post 类创建的所有新 DbContext?

Anyhow I've tried it both, but no success. When I created this new context I was doing following in PMC:

无论如何,我都尝试过,但没有成功。当我创建这个新上下文时,我正在 PMC 中执行以下操作:

Enable-Migrations
Add-Migration "PostMigration"
Update-Database

Usually, or all goes well, but I don't get any new table in database, or I get an error: AspNetUsers already exists, and AspNetUsers is one of auto-created tables that I've changed by adding new columns to it.

通常,或者一切顺利,但我在数据库中没有得到任何新表,或者我收到一个错误:AspNetUsers 已经存在,而 AspNetUsers 是我通过向其中添加新列而更改的自动创建的表之一。

Update: My context right now is in seperated class named PostContext and it looks like this:

更新:我的上下文现在位于名为 PostContext 的单独类中,它看起来像这样:

public class PostContext : DbContext
{
    public PostContext() : base("name=PostContext")
    {
    }

    public DbSet<Post> Posts { get; set; }
}

Second try:

第二次尝试:

Since my first approach didn't gave any result. I've tried doing what's described in this link. Adding mapping to my project:

由于我的第一种方法没有给出任何结果。我已尝试执行此链接中描述的操作。将映射添加到我的项目:

I've crated new class PostConfiguration for mapping:

我已经创建了用于映射的新类 PostConfiguration:

public class PostConfiguration : EntityTypeConfiguration<Post>
    {
        public PostConfiguration() : base()
        {
            HasKey(p => p.PostId);
            ToTable("Post");

            HasOptional(p => p.PostText);
            ToTable("Post");

            HasOptional(p => p.ImagePost);
            ToTable("Post");

            HasOptional(p => p.TextPost);
            ToTable("Post");

            HasOptional(p => p.FilePost);
            ToTable("Post");

            HasRequired(p => p.UserId);
            ToTable("Post");
        }
    }

In the class Post I've added context class too PostContext with modelBuilder variable as they've suggested in listed link above:

在 Post 类中,我也添加了上下文类 PostContext 和 modelBuilder 变量,正如他们在上面列出的链接中所建议的那样:

 public class PostContext : DbContext
    {
        static PostContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PostContext>());
        }

        public DbSet<Post> Posts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties()
                        .Where(p => p.Name == "Key")
                        .Configure(p => p.IsKey());

            modelBuilder.Configurations.Add(new PostConfiguration());
        }

   }

I've run all PMC commands again, and still no success, table Post is missing from default database.

我再次运行了所有 PMC 命令,但仍然没有成功,默认数据库中缺少表 Post。

回答by Oliver

What has happened here is that you had existing database tables before Migrations where enabled. So Entity Framework thinks that ALL your database objects need to created, this could be seen by opening up your PostMigration migration file.

这里发生的情况是,在启用迁移之前,您拥有现有的数据库表。所以实体框架认为你所有的数据库对象都需要创建,这可以通过打开你的 PostMigration 迁移文件来看到。

The best way is to trick EF into to doing the initial migration with every before you added the Post table and then do the Posts migration after.

最好的方法是在添加 Post 表之前诱使 EF 进行初始迁移,然后再进行 Posts 迁移。

Steps

脚步

  1. Comment out the Posts in the DBContext so EF doesn't know about posts

    //public DbSet<Post> Posts { get; set; }
    
  2. Enable Migrations

    Enable-Migrations
    
  3. Add an initial migration with all tables prior to your changes

    Add-Migration "InitialBaseline" –IgnoreChanges
    
  4. Now update the database, this will create a MigrationHistory table so that EF knows what migrations have been run.

    Update-Database
    
  5. Now you can uncomment the line in 1 to "Do your change"

  6. Create a new migration with the addition of Posts

    Add-Migration "PostMigration"
    
  7. Now do an update... and hopefully it should all work.

    Update-Database
    
  1. 注释掉 DBContext 中的帖子,这样 EF 就不知道帖子了

    //public DbSet<Post> Posts { get; set; }
    
  2. 启用迁移

    Enable-Migrations
    
  3. 在更改之前添加所有表的初始迁移

    Add-Migration "InitialBaseline" –IgnoreChanges
    
  4. 现在更新数据库,这将创建一个 MigrationHistory 表,以便 EF 知道已经运行了哪些迁移。

    Update-Database
    
  5. 现在您可以取消注释 1 中的行以“进行更改”

  6. 添加 Posts 创建一个新的迁移

    Add-Migration "PostMigration"
    
  7. 现在做一个更新......希望它应该一切正常。

    Update-Database
    

Now that migrations are all setup and they are baselined future migrations will be easy.

现在迁移都已设置好,并且它们是基线,未来的迁移将很容易。

For more information I found this link useful: http://msdn.microsoft.com/en-us/data/dn579398.aspx

有关更多信息,我发现此链接很有用:http: //msdn.microsoft.com/en-us/data/dn579398.aspx