实体框架:在运行时改变连接字符串 [英] Entity Framework : Change connection string at runtime

查看:158
本文介绍了实体框架:在运行时改变连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个使用实体框架6 code-第一的方针和StructureMap国际奥委会ASP.NET MVC应用程序。结果
同时它采用单位工​​作模式。
下面是codeS:结果

Assuming there is an ASP.NET MVC application that uses Entity Framework 6 with code-first approach and StructureMap as IoC.
Also It uses Unit Of Work pattern. Here are the codes :

域类搜索

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }        
 
    }

IUnitOfWork和的DbContext:

IUnitOfWork and DbContext :

    public interface IUnitOfWork
{
    IDbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges();
}

public class Sample07Context : DbContext, IUnitOfWork
{
    public DbSet<Product> Products { set; get; }

    #region IUnitOfWork Members

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }

    #endregion
}

在服务类业务逻辑:

   public interface IProductService
{
    void AddNewProduct(Product product);
    IList<Product> GetAllProducts();
}


    public class ProductService : IProductService
    {
        IUnitOfWork _uow;
        IDbSet<Product> _products;
        public ProductService(IUnitOfWork uow)
        {
            _uow = uow;
            _products = _uow.Set<Product>();
        }
 
        public void AddNewProduct(Product product)
        {
            _products.Add(product);
        }
 
        public IList<Product> GetAllProducts()
        {
            return _products.Include(x => x.Category).ToList();
        }
    }

在注入控制器中的服务类

Injecting the service class in controller

        public class HomeController : Controller
    {
        private IProductService _productService;
        private IUnitOfWork _uow;

        public HomeController(IUnitOfWork uow, IProductService productService)
        {
            _productService = productService;

            _uow = uow;
        }

        [HttpGet]
        public ActionResult Index()
        {
            var list = _productService.GetAllProducts();
            return View(list);
        }
    }

这是我们在app_start叫StructureMap配置:

StructureMap Configuration that we call in app_start :

       private static void initStructureMap()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For<IUnitOfWork>().HttpContextScoped().Use(() => new Sample07Context());
                x.ForRequestedType<IProductService>().TheDefaultIsConcreteType<EfProductService>();
            });
            //Set current Controller factory as StructureMapControllerFactory
            ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
        }

一切工作正常使用单个数据库但在我的情况下用户可以使用多个数据库,我指的是用户应该能够在运行时更改连接字符串。我们创造的每用户创建应用程序中的每个项目单独的数据库。结果现在的问题是,我们注入的DbContext的服务和来自的DbContext web.config中读取连接字符串,因此当用户更改数据库中,我们不能设置新的连接字符串的DbContext。结果
你有什么建议?

Everything works fine with single database but in my scenario user can use multiple databases, I mean the user should be able to change the connection string at runtime. We create separate database per each project that user creates in the application.
Now the problem is that we inject DbContext to service and DbContext reads connection string from web.config so when user changes the database we cannot set new connection string to the DbContext.
What do you suggest?

推荐答案

在我的经验,我在EF 6. 数据库首页模式>的DbContext 将象下面这样产生的,当我加入实体数据模型

In my experience, I used the Database First mode in EF 6. The DbContext would be generated like below when I add Entity Data Model.

public TestEntities()
            : base("name=TestEntities")
        {
        }

TestEntities 重新present的的ConnectionString 在App.config元素

The TestEntities represent the ConnectionString element in the App.Config

<connectionStrings>   
<add name="TestEntities" connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>

但你可以改变默认的code以下。

But you can change the default code to below.

public partial class TestEntities : DbContext
    {
        public TestEntities()
            : base("name=TestEntities")
        {
        }

        public TestEntities(string sConnectionString)
            : base(sConnectionString)
        {
        }

...}

所以,你有两个选择,以获得数据库连接。

So you got two options to getting DB connection.


  1. 使用默认。该EF会发现在配置文件中的连接字符串。

  1. using the default. The EF will find the connection string in the config file.

传递连接字符串的DbContext。

passing the connection string to DbContext.

在code看起来像下面。

The code look like below.

EntityConnection entityConn =DBConnectionHelper.BuildConnection();
using (var db = new TestEntities(entityConn.ConnectionString))
{
....
}

至于问题如何建立一个EntityConnection?。请参阅 MSDN EntityConnection

希望这是有帮助的。

感谢。

这篇关于实体框架:在运行时改变连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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