【问题标题】:Seeding my database as per the Entity code-first approach根据实体代码优先方法播种我的数据库
【发布时间】:2015-08-31 06:54:58
【问题描述】:

所以在我让向导从现有数据库创建模型后,我的Configuration.cs

namespace SnakeGame.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<SnakeGame.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(SnakeGame.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

我的数据库的模型是

namespace SnakeGame.Migrations
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

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

        public virtual DbSet<BannedIP> BannedIPs { get; set; }
        public virtual DbSet<GameLog> GameLogs { get; set; }
        public virtual DbSet<IP> IPs { get; set; }
        public virtual DbSet<Score> Scores { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<GameLog>()
                .Property(e => e.logText)
                .IsUnicode(false);

            modelBuilder.Entity<IP>()
                .HasMany(e => e.BannedIPs)
                .WithRequired(e => e.IP)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Score>()
                .Property(e => e.name)
                .IsUnicode(false);
        }
    }
}

尝试按照注释掉的说明进行操作,我将protected override void Seed(SnakeGame.Models.ApplicationDbContext context) 的正文更改为

        context.IPs.AddOrUpdate(
            i => i.id,
            new IP { id = 1, byte1 = 4, byte2 = 35, byte3 = 241, byte4 = 179 },
            new IP { id = 2, byte1 = 172, byte2 = 16, byte3 = 254, byte4 = 1 }
        );

        context.BannedIPs.AddOrUpdate(
            i => i.id,
            new BannedIP { id = 1, ipId = 1}
        );

        context.Score.AddOrUpdate(
            s => s.id,
            new Score {  id = 1, score1 = 12, name = "John Skeet" },
            new Score {  id = 2, score1 = 1923, name = "Steve Ballmer"}
        );

但我在context.IPscontext.BannedIPs 和context.Score 上都遇到了错误。我得到的错误是

SnakeGame.Models.ApplicationDbContext 不包含定义 为...

我正试图弄清楚如何解决它。我的 Migrations 文件夹的完整代码可以看到 here。我认为所有这些代码优先迁移的尝试都把我的项目搞得一团糟。废话。

【问题讨论】:

  • 你能显示完整的错误吗?

标签: c# asp.net asp.net-mvc entity-framework entity-framework-migrations


【解决方案1】:

您的实体都在 SnakeDb 上下文中定义,而不是 ApplicationDbContext 所以将您的种子更改为

protected override void Seed(SnakeGame.Migrations.SnakeDb context)
...

进行逆向工程后,您可能希望将内容移动到您希望应用具有的任何结构中。对我来说,我将 POCO 复制到单独的“实体”项目中,然后将 EF 和上下文内容移动到“数据”项目中,但您也可以将它们移动到不同的文件夹中。

其次,由于您对数据库进行了反向工程,因此您需要进行基线初始迁移。您可以注释掉 Up() 和 Down() 代码,也可以通过

生成
Add-Migration InitialCreate –IgnoreChanges

https://msdn.microsoft.com/en-us/data/dn579398.aspx#option1

【讨论】:

  • 更改为 protected override void Seed(SnakeDb context) 会产生错误“找不到类型或命名空间 'SnakeDb'(您是否缺少 using 指令或程序集引用)”
  • 嗯,是的,你需要使用 SnakeGame.Migrations;或为上下文名称添加前缀。请参阅编辑后的答案。从长远来看,您可能应该将您的上下文移出 Migrations 文件夹。
【解决方案2】:

您是否使用迁移更新了数据库?我的项目中有一个命令示例

/*
* X DATA CONTEXT 
*/

//this command enables migrations
Enable-Migrations -StartUpProjectName X.Web -ProjectName X.DAL.Repository -EnableAutomaticMigrations -ContextTypeName XDataContext -Verbose -MigrationsDirectory:XDataContextMigrations

//this command create a new migration, please set up the name of the DBMigration
Add-Migration [NAME] -StartUpProjectName X.Web -ProjectName X.DAL.Repository -ConfigurationTypeName XUpdateDatabaseInitializer -Verbose 

//this command updates the current database
Update-Database -StartUpProjectName X.Web -ProjectName X.DAL.Repository -ConfigurationTypeName XUpdateDatabaseInitializer -Verbose 

//this command rollbacks the current Database to Specific Target applying Down() methods
Update-Database –TargetMigration: SpecificTargetMigrationName -StartUpProjectName X.Web -ProjectName X.DAL.Repository -ConfigurationTypeName XUpdateDatabaseInitializer -Verbose 

因此,如果您已经更新了数据库,我建议您完全删除当前数据库并使用迁移命令重新创建它...

希望对你有帮助。

【讨论】:

  • 您是否将该脚本保存在文件中或其他内容中?当您通过 Visual Studio 构建/编译/部署/无论您的项目时,有没有办法让它运行?
  • 致@Retired_MSFT_Millionaire:我将此脚本保存在靠近迁移目录的文件中,以便在需要时运行所需的命令(添加、更新或回滚)。致 Steeve:我没有意识到他使用了错误的 DbContext,所以,别担心,你的答案是对的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 2014-01-06
  • 1970-01-01
相关资源
最近更新 更多