Code-First Migration Process: What part am I missing?

后端 未结 1 933
北荒
北荒 2021-01-25 21:35

My steps:

1) Create my database in SSMS with the query

/* Execute in SQL Server Management Studio prior to building data model(s) */

C         


        
相关标签:
1条回答
  • 2021-01-25 22:32

    Your database context definition should look something like this:

    public class ApplicationDbContext: DbContext
    {
        public ApplicationDbContext() : base("connectionString")
        {
        }
    
        public DbSet<Scores> Scores { get; set; }
        public DbSet<GameLogs> GameLogs { get; set; }
        public DbSet<IPs> IPs { get; set; }
        public DbSet<BannedIPs> BannedIPs { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
    

    it inherits from DbContext and defines the structure of your object model.

    Your DbSet(s) should be mapped to your classes:

    • Scores
    • GameLogs
    • IPs
    • BannedIPs

    As you can see the constructor needs a connection string:

    public ApplicationDbContext() : base("connectionString")
    {
    }
    

    which must be defined in your web.config (or app.config):

    <connectionStrings>
        <add name="connectionString" connectionString="Server=localhost;Database=MigrationsTest;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    inside <configuration> section. I've used localhost here but, of course, you can use your remote database.

    Now from Package Manager Console you must have enabled the migration with Enable-Migrations.
    This command will build the configuration file which should look something like this:

    internal sealed class Configuration : DbMigrationsConfiguration<MigratingDatabase.SchoolContext>
    {
            public Configuration()
            {
                AutomaticMigrationsEnabled = true;
            }
    
            protected override void Seed(MigratingDatabase.SchoolContext context)
            {
    
            }
    }
    

    what I can see in your Configuration class it inherits from the database context:

    DbMigrationsConfiguration<SnakeGame.Models.ApplicationDbContext>
    

    but it is trying to seed a different object:

    protected void Seed (SnakeGame.Migrations.SnakeDB context)
    {
    
    }
    

    and, I guess, it should be:

    protected void Seed (SnakeGame.Models.ApplicationDbContext context)
    {
    
    }
    

    when everything is in place you can run:

    Update-Database -Verbose
    

    and it should build the database for you.

    Another thing you have to do to enable the migration is change the constructor of the configuration class:

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }
    

    using AutomaticMigrationsEnabled = true.

    0 讨论(0)
提交回复
热议问题