实体框架code首先没有的app.config [英] Entity Framework Code First without app.config

查看:250
本文介绍了实体框架code首先没有的app.config的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能够帮助我,因为它似乎我完全卡住了​​。

I hope somebody is able to help me, because it seems I'm totally stuck.

有关我们公司即将开展的项目,我们希望使用实体框架5与code第一种方法。我打了周围一小会儿,每次我尝试使用EF与我们现有的图书馆,我会失败,因为它似乎EF很大程度上依赖于现有的a​​pp.config。

For upcoming projects in our company we'd like to use Entity Framework 5 with an code first approach. I played around a little while and everytime I try to use EF with our existing libraries, I fail because it seems EF heavily relies on an existing app.config.

在我们公司,我们有一个室内的数据库库,使我们能够连接到各种数据源和数据库技术,以MEF(托管扩展框架)的优势,为数据库提供。我只是通过一些数据库设置,如主机(或文件),目录,用户凭证和数据库供应商的名称,该库查找相应的插件,并返回我的自定义连接字符串或的IDbConnection。 我们希望一起使用这个库与EF,因为它使我们能够灵活哪个数据库中,我们也使用在运行时更改数据库。

In our company, we have an inhouse database library that allows us to connect to various data sources and database technologies taking the advantages of MEF (managed extensibility framework) for database providers. I just have to pass some database settings, such as host (or file), catalog, user credentials and a database provider name, the library looks for the appropriate plugin and returns me a custom connection string or IDbConnection. We'd like to use this library together with EF because it allows us to be flexible about which database we use also change the database at runtime.

所以。我看到一个典型的DbContext对象需要在构造函数中没有参数。它会自动查找在app.config中适当的连接字符串。我们不喜欢这样的事情让我改变了默认构造函数采取这种获得传递给此的DbContext基类的DbConnection对象。没有成交。

So. I saw that a typical DbContext object takes no parameters in the constructor. It automatically looks for the appropriate connection string in app.config. We don't like such things so I changed the default constructor to take a DbConnection object that get's passed to the DbContext base class. No deal.

问题出现code第一种模式改变时。 EF自动注意到这一点,并寻找移民类/配置。但是:一个典型的移民类需要一个默认的无参数的构造函数的情况下!真可惜!

Problems occur when the code first model changes. EF automatically notices this and looks for migration classes / configuration. But: A typical migration class requires a default parameterless constructor for the context! What a pity!

因此​​,我们使用IDbContextFactory接口建立我们自己的迁移类。但同样,这似乎也是这个IDbContextFactory需要一个参数的构造函数,否则我不能添加迁移或更新数据库。

So we build our own migration class using the IDbContextFactory interface. But again, it seems that also this IDbContextFactory needs a parameterless constructor, otherwise I'm not able to add migrations or update the database.

另外,我做我自己的数据迁移的配置,我传递的背景下,也是目标数据库。问题就在这里:它没有找到任何迁移类,不管我怎么努力

Further, I made my own data migration configurator where I pass the context, also the target database. Problem is here: It doesn't find any migration classes, no matter what I try.

我完全卡住,因为它似乎使用EF是当连接字符串保存在app.config中的唯一途径。这是愚蠢的,因为我们需要改变数据库连接在运行时和的app.config是只读的缺省用户!

I'm completely stuck because it seems the only way to use EF is when connection strings are saved in app.config. And this is stupid because we need to change database connections at runtime, and app.config is read-only for default users!

如何解决此问题?

推荐答案

答案就在这里提供了

http://stackoverflow.com/a/15919627/941240

关键是要稍微修改默认的 MigrateDatabaseToLatestVersion 初始化这样:

The trick is to slightly modify the default MigrateDatabaseToLatestVersion initializer so that:

  • 数据库总是被初始化...
  • ...使用连接字符串从当前上下文

DbMigrator 仍然会创建一个新的数据范围内,但会根据初始化复制连接字符串从你的背景。我甚至能够缩短code。

The DbMigrator will still create a new data context but will copy the connection string from yours context according to the initializer. I was even able to shorten the code.

和这里有云:

public class MasterDetailContext : DbContext
{
    public DbSet<Detail> Detail { get; set; }
    public DbSet<Master> Master { get; set; }

    // this one is used by DbMigrator - I am NOT going to use it in my code
    public MasterDetailContext()
    {
        Database.Initialize( true );
    }

    // rather - I am going to use this, I want dynamic connection strings
    public MasterDetailContext( string ConnectionString ) : base( ConnectionString )
    {
        Database.SetInitializer( new CustomInitializer() );
        Database.Initialize( true );
    }

    protected override void  OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

public class CustomInitializer : IDatabaseInitializer<MasterDetailContext>
{

    #region IDatabaseInitializer<MasterDetailContext> Members

    // fix the problem with MigrateDatabaseToLatestVersion 
    // by copying the connection string FROM the context
    public void InitializeDatabase( MasterDetailContext context )
    {            
        Configuration cfg = new Configuration(); // migration configuration class
        cfg.TargetDatabase = new DbConnectionInfo( context.Database.Connection.ConnectionString, "System.Data.SqlClient" );

        DbMigrator dbMigrator = new DbMigrator( cfg );
        // this will call the parameterless constructor of the datacontext
        // but the connection string from above will be then set on in
        dbMigrator.Update();             
    }

    #endregion
}

客户端code:

Client code:

    static void Main( string[] args )
    {

        using ( MasterDetailContext ctx = new MasterDetailContext( @"Database=ConsoleApplication801;Server=.\SQL2012;Integrated Security=true" ) )
        {
        }

        using ( MasterDetailContext ctx = new MasterDetailContext( @"Database=ConsoleApplication802;Server=.\SQL2012;Integrated Security=true" ) )
        {
        }
    }

运行,这将导致根据该迁移配置来创建和迁移的两个数据库

Running this will cause the two databases to be created and migrated according to the migration configuration.

这篇关于实体框架code首先没有的app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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