数据库在EF 6.0.2和6.1之间创建不同 [英] Database create different between EF 6.0.2 and 6.1

查看:185
本文介绍了数据库在EF 6.0.2和6.1之间创建不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来,与6.0.2相比,EF 6.1在意外的时候创建了数据库。我需要一种检查数据库是否创建的方法。如果没有创建,我创建它并运行一些播种代码。我升级到6.1,这个逻辑不再有效。

It seems that the database is created at an unexpected time with EF 6.1 compared to 6.0.2. I need a way to check to see if the database is created. If it is not created, I created it and run some seeding code. I upgraded to 6.1 and this logic no longer works.

我使用6.0.2创建了一个简单的项目,然后复制了该项目,更新了EF,您可以看到差异。

I created a simple project using 6.0.2 and then copied that project, updated EF and you can see the difference.

对于这两个项目,我先使用代码,创建迁移,然后运行解决方案。第一次看到数据库没有创建并创建它并种子。问题是用于检查DB是否创建的代码实际上在使用6.1时创建了DB。因此,支票总是返回true并且播种代码永远不会运行。

For both projects I use code first, create the migration and then run the solution. The first time it should see that the DB has not been created and create it and seed it. The issue is that the code that is used to check if the DB is created actually creates the DB when using 6.1. Because of this, the check always returns true and the seeding code is never ran.

控制台应用程序:

Program.cs

Program.cs

namespace SimpleEFTest2
{
    class Program
    {
        static void Main(string[] args)
        {
            MyContext.InitializeDatabase();
        }
    }
}

TestEntity.cs: p>

TestEntity.cs:

namespace SimpleEFTest2
{
    public class TestEntity
    {
        public int Id { get; set; }
        public string SomeValue { get; set; }
    }
}

MyContext.cs:

MyContext.cs:

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

namespace SimpleEFTest2
{
    public class MyContext: DbContext
    {
        public DbSet<TestEntity> TestEntities { get; set; }

        public ObjectContext ObjectContext
        {
            get
            {
                //With EF 6.0.2 this would throw an exception if the DB didn't exist.
                //With EF 6.1.0 this creates the database, but doesn't seed the DB.
                return ((IObjectContextAdapter)this).ObjectContext;
            }
        }

        private static readonly Object syncObj = new Object();
        public static bool InitializeDatabase()
        {
            lock (syncObj)
            {
                using (var temp = new MyContext())
                {
                    ObjectContext oc = null;
                    try
                    {
                        oc = temp.ObjectContext;
                    }
                    catch (Exception ex)
                    {
                        //Ignore error
                        Console.WriteLine(ex);
                    }
                    //If oc != null && oc.DatabaseExists() return else create and seed DB
                    //With EF 6.1, oc.DatabaseExists() is always true because it was created in the function that gets the ObjectContext.
                    return true;
                }
            }
        }
    }
}

Configuration.cs

Configuration.cs

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

    internal sealed class Configuration : DbMigrationsConfiguration<SimpleEFTest2.MyContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(SimpleEFTest2.MyContext myContext)
        {
            var entity = myContext.TestEntities.FirstOrDefault(i => i.SomeValue == "123");
            if (entity == null)
            {
                entity = new TestEntity { SomeValue = "123" };
                myContext.TestEntities.Add(entity);
            }
            myContext.SaveChanges();
        }
    }
}


推荐答案

我不知道为什么我没有看到这个...

I'm not sure why I didn't see this before...

DbContext.Database有一个方法Exists()。这将返回正确的结果而不创建数据库。我更改了代码以使用它,现在的6.0.2和6.1.0都是一样的。

DbContext.Database has a method Exists(). This will return the correct result without creating the database. I changed the code to use that and now 6.0.2 and 6.1.0 both work the same.

新的MyContext.cs:

New MyContext.cs:

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using SimpleEFTest2.Migrations;

namespace SimpleEFTest2
{
    public class MyContext: DbContext
    {
        public DbSet<TestEntity> TestEntities { get; set; }

        public ObjectContext ObjectContext
        {
            get
            {
                //With EF 6.0.2 this would throw an exception if the DB didn't exist.
                //With EF 6.1.0 this creates the database, but doesn't seed the DB.
                return ((IObjectContextAdapter)this).ObjectContext;
            }
        }

        private static readonly Object syncObj = new Object();
        public static bool InitializeDatabase()
        {
            lock (syncObj)
            {
                using (var temp = new MyContext())
                {
                    if (temp.Database.Exists()) return true;

                    var initializer = new MigrateDatabaseToLatestVersion<MyContext, Configuration>();
                    Database.SetInitializer(initializer);
                    try
                    {
                        temp.Database.Initialize(true);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        //Handle Error in some way
                        return false;
                    }
                }
            }
        }
    }
}

这篇关于数据库在EF 6.0.2和6.1之间创建不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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