简体   繁体   English

根据实体代码优先方法播种我的数据库

[英]Seeding my database as per the Entity code-first approach

So after I had the wizard create models from an existing database my Configuration.cs was 所以,当我有了向导从现有数据库创建模型后,我的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" }
            //    );
            //
        }
    }
}

and the model of my database was 我的数据库模型是

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

Trying to follow the commented out instructions, I changed the body of protected override void Seed(SnakeGame.Models.ApplicationDbContext context) to 尝试遵循注释掉的说明,我将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"}
        );

but I'm getting errors on each of context.IPs , context.BannedIP s and context.Score . 但是我在context.IPscontext.BannedIPcontext.Score上都遇到了错误。 The error I'm getting is 我得到的错误是

SnakeGame.Models.ApplicationDbContext does not contain a definition for ... SnakeGame.Models.ApplicationDbContext不包含以下定义...

and I'm trying to figure out how to fix it. 而且我正在尝试找出解决方法。 The full code of my Migrations folder can be seen here . 我的Migrations文件夹的完整代码可以在这里看到。 I think I've royally messied up my project by all these attempts at code-first migration. 我认为通过所有这些代码优先迁移的尝试,我已经弄乱了我的项目。 Blah. 等等。

Your entities are all defined in the SnakeDb context, not ApplicationDbContext so change your seed to 您的实体都是在SnakeDb上下文中定义的,而不是在ApplicationDbContext中定义的,因此请将您的种子更改为

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

After you reverse engineer, you may want to move things into whatever structure you want your app to have. 进行反向工程后,您可能希望将事物移动到应用程序想要的任何结构中。 For me, I copy the POCOs to a separate "Entity" project and then move the EF and context stuff to a "Data" project, but you could also just move them into different folders. 对我来说,我将POCO复制到单独的“实体”项目中,然后将EF和上下文内容移动到“数据”项目中,但是您也可以将它们移动到不同的文件夹中。

Second, since you reverse engineered the database, you will need a baseline initial migration. 其次,由于对数据库进行了反向工程,因此需要进行基线初始迁移。 You can either comment out the Up() and Down() code or you can generate via 您可以注释掉Up()和Down()代码,也可以通过

Add-Migration InitialCreate –IgnoreChanges

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

Did you update your DB with your migrations?? 您是否通过迁移更新了数据库? I have an example of the commands in my proyects 我有一个例子在我的proyects

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

So, if you already updated your DB I'd suggest you to completely delete your current DB and recreate it using Migrations commands... 因此,如果您已经更新了数据库,建议您完全删除当前数据库,然后使用“迁移”命令重新创建它。

Hope it helps. 希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过具有多对多关系的实体框架代码优先方法为 SQL Server 播种 - Seeding SQL Server by Entity Framework code-first approach with many-to-many relationship 我的数据库不是通过Entity Framework 6代码优先方法自动创建的吗? - My database is not getting automatically created by Entity Framework 6 code-first approach? 实体未使用“代码优先”方法更新 - Entity not updating using Code-First approach 播种代码优先数据库导致错误 --&gt; 无法添加实体类型“$name”的种子实体,因为它设置了导航“$name” - Seeding code-first database leads to an error --> The seed entity for entity type '$name' cannot be added because it has the navigation '$name' set 是否可以在不使用Entity Framework中以代码优先方式使用C#属性的情况下生成数据库字段? - Is it possible to generate database fields without using C# properties in Entity Framework, code-first approach? 如果我们使用具有代码优先方法的Entity框架,是否可以在给定路径上创建数据库(Sql Server compact)? - Is possible to create a database (Sql Server compact) on a given path if we use Entity framework with code-first approach? 如何使用 Entity Framework Code-First 方法将 double[] 数组存储到数据库 - How to store double[] array to database with Entity Framework Code-First approach 实体框架代码优先数据库未更新 - Entity Framework Code-First Database Not Updating 实体框架 5 代码优先不创建数据库 - Entity Framework 5 code-first not creating database 实体框架优先代码和现有数据库 - Entity Framework code-first and existing database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM