Entity Framework DbContext dynamic instantiation with custom Connection String

天涯浪子 提交于 2019-12-11 06:07:26

问题


Migrating from ObjectContext to DbContext code-generation, I realized that context class generated (which inherits from DbContext) has no constructor that receives connectionString neither EntityConnection (like ObjectContext child class had).

This is a problem in my application since I need to instantiate my context dynamically from the concrete Type, using a runtime generated connection string.


回答1:


On your class that inherits the DbContext, you should be able to specify the base constructor that takes the connection sting:

public class MyDbContext : DbContext
{
    public MyDbContext(string connString)
        : base(connString)
    {
    }
}

You will have to use the SQLConnection builder though:

SqlConnectionStringBuilder connBuilder= new SqlConnectionStringBuilder(dbConnString);

And use it in your constructor:

MyDbContext dbContext = new MyDbContext(connBuilder.ToString());



回答2:


This helped me:

 public MyDatabaseContext():base("name=MyConnectionString")
  {
  }


来源:https://stackoverflow.com/questions/16341163/entity-framework-dbcontext-dynamic-instantiation-with-custom-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!