简体   繁体   English

Entity Framework 6中的DbContext和数据库初始化器

[英]DbContext and database initalizer in Entity Framework 6

Where is the proper place to call 合适的通话地点在哪里

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());?

Below is description of architecture for my project. 以下是我的项目的架构说明。

I have MVC + webAPI project, where Data Access Layer is seperate project and it uses Entity Framework 6.1.3. 我有MVC + webAPI项目,其中数据访问层是单独的项目,它使用Entity Framework 6.1.3。 I have defined class MyDbContext : 我定义了类MyDbContext

public class EedezDbContext : System.Data.Entity.DbContext

I have also Configuration class with Seed method. 我也有带有Seed方法的Configuration类。

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

        protected override void Seed(Eedez.Dal.DbContext.EedezDbContext context)
        {
            // running seeds
        }
    }

DataAccessLayer also has DataAccessors that calls entity framework methods to make operations with data. DataAccessLayer还具有DataAccessors ,它调用实体框架方法来对数据进行操作。 Each method of dataaccessor creates instance of MyDbContext . dataaccessor的每种方法都会创建MyDbContext实例。 For instance, here is one base accessor method: 例如,这是一个基本的访问器方法:

 public class AccessorBase<T> : IAccessorBase<T> where T : BaseEntity
    {
       public virtual IEnumerable<T> GetByFilter(Expression<Func<T, bool>> filter)
        {
            using (MyDbContext context = new MyDbContext())
            {
                return IncludeRefObjects(context.Set<T>()).Where(filter).ToList();
            }
        }     
...
}

I am not sure where to add database initializer. 我不确定在哪里添加数据库初始化程序。 Most of the examples I have found add database initializer into global.asax, but this is not my case, because Data Access Layer is in separate project. 我发现的大多数示例都将数据库初始化程序添加到global.asax中,但这不是我的情况,因为数据访问层位于单独的项目中。 To run project for now, I haved add initalizer here: 现在要运行项目,我必须在此处添加initalizer:

public class MyDbContext : System.Data.Entity.DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Company> Companies { get; set; }
    ...

    public MyDbContext()
        : base("MyDb")
    {
        var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Configurations.Add(new CompanyConfig());
        modelBuilder.Configurations.Add(new UserConfig());
        ...

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());
    }

Is this the right place? 这是对的地方吗?

Set in your DbContext s static constructor. 在您的DbContext的静态构造函数中设置。 This method just calls one time and automatically just before you first time use your class. 该方法仅调用一次,并且在您第一次使用类之前自动调用。

public class MyDbContext : System.Data.Entity.DbContext
{
    static MyDbContext()
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());
    }

    // your other code
    public MyDbContext()
    : base("MyDb")
    {
        var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
    }
    // ..
}

I usually prefer to configure the initializer database within EntityFramework configuration section on web.config file, for example: 我通常更喜欢在web.config文件的EntityFramework配置部分中配置初始化程序数据库,例如:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <contexts>
      <context type="MyAssembly.Fullname.EedezDbContext, MyAssembly.Fullname">
        <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyAssembly.Fullname.EedezDbContext, MyAssembly.Fullname], [MyAssembly.Fullname.Configuration, MyAssembly.Fullname ]], EntityFramework" />
      </context>
    </contexts>
</entityFramework>

If you find it very difficult to write the full assembly qualified name type, just you can use this code to get it: 如果发现编写完整的程序集限定名称类型非常困难,则可以使用以下代码来获取它:

var configInitializer =  typeof (MigrateDatabaseToLatestVersion<EedezDbContext, Configuration>).AssemblyQualifiedName;

and paste this value on type property of databaseInitializer element. 并将此值粘贴到databaseInitializer元素的type属性上。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM