使用EF 6和MVC 5中的Code First方法将新表添加到现有数据库中 [英] Add new table to an existing database using Code First approach in EF 6 and MVC 5

查看:273
本文介绍了使用EF 6和MVC 5中的Code First方法将新表添加到现有数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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:

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; }
    } 

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

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:

<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" />

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

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

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

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

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

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

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.

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

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

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

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

第二次尝试:

由于我的第一种方法没有产生任何结果.我已经尝试执行此链接中所述的内容.将映射添加到我的项目中:

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

我创建了新类PostConfiguration进行映射:

I've crated new class PostConfiguration for mapping:

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");
        }
    }

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

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

 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());
        }

   }

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

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

推荐答案

在这里发生的事情是,在启用迁移"之前,您已有现有的数据库表. 因此,Entity Framework认为您需要创建所有数据库对象,这可以通过打开PostMigration迁移文件来看到.

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.

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

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.

  1. 在DBContext中注释帖子,以使EF不了解帖子

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

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

  • 启用迁移

  • Enable Migrations

    Enable-Migrations
    

  • 在更改之前为所有表添加初始迁移

  • Add an initial migration with all tables prior to your changes

    Add-Migration "InitialBaseline" –IgnoreChanges
    

  • 现在更新数据库,这将创建一个MigrationHistory表,以便EF知道已运行了哪些迁移.

  • Now update the database, this will create a MigrationHistory table so that EF knows what migrations have been run.

    Update-Database
    

  • 现在您可以取消注释1中的行以进行更改"

  • Now you can uncomment the line in 1 to "Do your change"

    通过添加帖子来创建新的迁移

    Create a new migration with the addition of Posts

    Add-Migration "PostMigration"
    

  • 现在进行更新...,希望它可以正常工作.

  • Now do an update... and hopefully it should all work.

    Update-Database
    

  • 现在,所有迁移均已完成,并且已将它们作为基准,以后的迁移将变得容易.

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

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

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

    这篇关于使用EF 6和MVC 5中的Code First方法将新表添加到现有数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆