Thursday, March 24, 2016

Change database in connectionstring from app

Leave a Comment

I have created a Xamarin where I want to query one database on a Azure SQL Server and regarding which result I get back I want to query one of X numbers of certain databases.

So far I have been able to create two different APIs where the first API gets information from the first database.

And I have hardcoded (in the TableController) to use one specific database (in the same SQL Server).

  string dbString = "database2";   myContextClass context = new myContextClass(dbString); 

This works like a charm. However. I would like to be able to pass which database I want to connect to from my app.

I.e. when calling my mobileservice all I do is this:

 this.client = new MobileServiceClient(                 Constants.DatabaseURL); 

Is there something I can add to this methodcall that will set the database connectionstring in the controller?

2 Answers

Answers 1

You should not be connecting to the database from the mobile App, you should have a backend REST service built for example using Web API and hosted in Azure API Service, this is where the connection to the database will occur, and the connection string will be added to the web.config file which can be easily changed from the Azure portal.

Answers 2

I think you need 2 dbContext instances. Here is an example in the controller how to initialize 1 dbContext. So, I guess, you could have the parameter you want to specify which db you want, and use the main controller or call another controller which is initialized with the other dbContext. (or try overwriting the DomainManager with different context)

 public class TodoItemController : TableController<TodoItem>     {         protected override void Initialize(HttpControllerContext controllerContext)         {             base.Initialize(controllerContext);             AppContext context = new AppContext();             DomainManager = new EntityDomainManager<TodoItem>(context, Request);         }          // GET tables/TodoItem         public IQueryable<TodoItem> GetAllTodoItems()         {             return Query();         } 

Then you have 2 dbContext instances like this:

public class AppContext : DbContext     {         private const string connectionStringName = "Name=MS_TableConnectionString";          public NeptuneAppContext() : base(connectionStringName)         {         }  

where you can specify different connectionStrings. Hope it helps

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment