Code First Migrations and initialization error

前端 未结 3 1447
眼角桃花
眼角桃花 2020-12-24 03:44

I\'m unsure about how to use the code first migration feature. In my understanding it should create my database if it\'s not existing already, and update it to the latest sc

3条回答
  •  滥情空心
    2020-12-24 04:10

    I played around with the code you provided and in this case (with SQL Server instead of CE) and have arrived at the following. I've removed the Database.Create code and allowed EF's automatic migrations to do it's thing. This runs through and calls the Seed method correctly now.

    internal class Program
    {
        private static void Main()
        {
            EntityFrameworkProfiler.Initialize();
    
            Database.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlServer");
            Database.SetInitializer(new MigrateDatabaseToLatestVersion());
    
            using (var context = new MyContext())
            {
                var element = context.Dummies.FirstOrDefault();
            }
        }
    }
    
    internal class Dummy
    {
        public String Id { get; set; }
    }
    
    internal sealed class MyContext : DbContext
    {
        public MyContext() : base(@"Data Source=localhost;Initial Catalog=Dummies;User Id=;Password=;MultipleActiveResultSets=False;")
        {
        }
    
        public DbSet Dummies { get; set; }
    }
    
    internal sealed class MyContextConfiguration : DbMigrationsConfiguration
    {
        public MyContextConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    
        protected override void Seed(MyContext context)
        {
            context.Dummies.AddOrUpdate(new Dummy() { Id = "First" });
        }
    }
    

    If you look in EF profiler, you'll see there are more queries run against the DB now (and even a check for the old EdmMetaData table... which is very odd, as it should drop that table if it's encountered now in favour of the __MigrationHistory table). I don't know why this is happening, I guess it's either a configuration issue our side (of which I don't yet know how to fix) or it's a bug in the migrations code.

    So, I think with EF migrations we're either left to code based migrations (see my blog post here) or automatic migrations (as this code snippet demonstrates). I guess as time goes on I'll get a better understanding of why EF (or the way I migrate) has this strange behaviour - or EF itself will get better as it evolves.

提交回复
热议问题