none
Passing connection string to Entity framework at runt time for each call RRS feed

  • Question

  • My Entity framework context is as following

     public partial class MyContext : DbContext, IMyContext
    {
        static MyContext()
        {
            System.Data.Entity.Database.SetInitializer<MyContext>(null);
        }
    
        public MyContext()
            : base("Name=MyContext")
        {
        }

    I am resolving it through autofac in the following way

    builder.RegisterType(typeof(MainContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            builder.RegisterType<MainContext>().As<IMainContext>().InstancePerRequest();

    This db context gets called in repository layer

    #region Fields
    
        private readonly IMyContext _context;
    
        #endregion
    
        #region Constructors and Destructors
    
        public EmployeeRepository(IMyContext context)
        {
            _context = context;
        }
    
        #endregion
    
        public void Create(Employee emp)
        {
            this._context.Employee.Add(emp);
        }

    Now my issue is , I want to set the connection string dynamically per call. The connection string will be passed through a webapi which i want to pass on to this context. Can anyone help me how can i do that? I am confused about autofac here. Secondly how can i make sure each call sets connection string and does not cache it.

    • Moved by Kristin Xie Friday, June 19, 2015 3:36 AM move to appropriate forum
    Wednesday, June 17, 2015 11:18 PM

Answers

  • The DbContext class contains constructors that take the connection string or connection object. Therefore you can add a corresponding constructor to MyContext. If MyContext is auto-generated, then derive another class from MyContext containing all of required constructors.

    It is probably not blamable to use the context in normal old-fashioned way:

        using( var context = new MyContext(some-connection-string-or-object) )
        {
            context.Employee.Add(emp);
            . . .
        }

    Thursday, June 18, 2015 6:10 AM