Sneha K

Sneha K

  • 1.2k
  • 527
  • 196.7k

Change database in db.Context file dynamically in run time

May 1 2018 10:27 AM
Hi i want to change database name dynamically in db.context file in asp.net mvc.I am passing database name dynamically in db.context file. It is working but once i refresh the edmx file means my dynamic coding is automatically cleared in db.context file. i want to change database dynamically in run time in asp.net mvc. Here i tried in db.context file its working but once i update or refresh the edmx means it clear my code.
 
My Connection string code in web.config file
  1. <connectionStrings>  
  2. <add name="CRMEntities" connectionString="Data Source=192.168.0.73\SQLEXPRESS,14330;Initial Catalog=CRM;User ID=sa;Password=wafewin;  
  3. MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" />  
  4. </connectionStrings>  
My Coding in db.context file
 
MyCRM
  1. namespace CostToWafe  
  2. {  
  3. using System;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. public partial class CRMEntities : DbContext  
  7. {  
  8. public CRMEntities() : base()  
  9. {  
  10. this.Database.Connection.ConnectionString = "Presist Security Info=False;User ID =sa;Password=**"+GLOBAL.ZDATABASE+"**;Intial Catalog=SS1718;Data Soure=192.168.70.41";  
  11. }  
  12. protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  13. {  
  14. throw new UnintentionalCodeFirstException();  
  15. }  
  16. public virtual DbSet<Address> Addresses { getset; }  
  17. public virtual DbSet<AddressType> AddressTypes { getset; }  
  18. public virtual DbSet<Area> Areas { getset; }  
  19. public virtual DbSet<Bank> Banks { getset; }  
  20. public virtual DbSet<City> Cities { getset; }  
  21. public virtual DbSet<ContactType> ContactTypes { getset; }  
  22. }  
  23. }  
In this GLOBAL.ZDATABASE i pass the database name dynamically in run time. Its working but one i update or fresh edmx file means this code is cleared automatically.
 
My Controller code
 
Visitors form Controller
  1. public class VisitorsFormController : Controller  
  2. {  
  3. CRMEntities db = new CRMEntities();  
  4. // GET: /VisitorsForm/  
  5. public ActionResult Index()  
  6. {  
  7. return View()  
  8. }  
  9. }  
Now my doubt is it possible to connect multiple database dynamically in db.context file or any other place without change in web.config file in run time
 
Anyone please help me to resolve this issue to change database name dynamically in db.context file and connect in controller and also please tell another method to change database dynamically in runtime mvc .
 
Thanks all

Answers (2)