Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Dynamically Changing Entity Framework Connection String

Posted on 2012-08-27
6
Medium Priority
?
2,610 Views
Last Modified: 2013-01-28
I've been searching for a solution for a few hours now to what seems to be a very simple problem with no luck.

I'm using Visual Studio 2012, VB.net, .Net 4.5, Entity Framework 5, dbContext (generated from the designer) and SQL Server Express to create a web app.

I have 1 "MasterDb" that stores registration information for each client who signs up with my service and allows them to administer their account.  It also stores their "ClientId" which is a unique number assigned to each client.

Each client will have their own separate but identical database which will be dynamically created when they sign up.  Each database will have a name something like "ClientDb_0001", "ClientDb_0002", etc.  The trailing number will be the "ClientId" I mentioned.  What I need to do is override the connection string entity framework uses once the user logs in with my dynamically created string so that they can use their own database.  I've read some posts talking about passing a connection string to dbContext but I don't understand how this is possible.

The way I currently use ef is as follows:

Using dbContext As New myEntities
    Dim res = (from myVals In dbContext.myTable
                     where myVals.id = someid
                     select myVal).FirstOrDefault
End Using

Open in new window


How in the world can I pass a connection string to this?

Thanks for any help anyone can provide,
Casey
0
Comment
Question by:thesnoman
5 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 38338973
You need to override the CreateObjectContext as shown in http://forums.silverlight.net/t/211959.aspx/1
0
 

Author Comment

by:thesnoman
ID: 38339024
Thanks for the reply however this method doesn't seem to work for me.  When I attempt to override CreateObjectContext() of my entities I get the following error:

function 'CreateObjectContext' cannot be declared 'Overrides' because it does not override a function in a base class

I don't know if this is because I'm using EF 5 or if I'm just doing something wrong or what.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38339859
What class is your myEntities deriving from? I think there is an overloaded constructor on the base class which takes in the connection string. So you can add a constructor to your myEntities class which takes a connection string and passes it to the base class.
0
 

Accepted Solution

by:
thesnoman earned 0 total points
ID: 38340701
I've found what seems to be a solution. I build a connection string such as:

 
Dim sqlBuilder As New SqlConnectionStringBuilder
    sqlBuilder.DataSource = clientDbDataSource
    sqlBuilder.InitialCatalog = "ClientDb_" & companyId
    sqlBuilder.IntegratedSecurity = True
    sqlBuilder.MultipleActiveResultSets = True
    sqlBuilder.ApplicationName = "EntityFramework"

Dim ecs As New EntityConnectionStringBuilder
    ecs.Provider = "System.Data.SqlClient"
    ecs.ProviderConnectionString = sqlBuilder.ToString
    ecs.Metadata = "res://*/Model.ClientDb.csdl|res://*/Model.ClientDb.ssdl|res://*/Model.ClientDb.msl"

Open in new window



I then created the following class based off of some examples I found on the web:

Public Class ClientDbEntities
    Inherits DbContext
    Public Sub New(ByVal connString As String)
        MyBase.New(connString)
    End Sub
End Class

Open in new window



And now I can pass a connection string as follows:

Using dbContext As New ClientDbEntities(ecs.ToString)

   Dim ui = (From cui In dbContext.client_custom_UserInfo
      Where cui.UserId = user.ProviderUserKey
      Select cui).FirstOrDefault
End Using

Open in new window


I hope this helps someone else!  Is it ok to take the dbContext I'm creating and save it as a module scoped variable or would this cause the connection to the database to stay open?  I would continue to use "using" when I need it, I would just like to avoid recreating it each time it's used if possible.

One thing I've found that I've not yet figured out is how to avoid issues if 2 databases have tables identically name and their structure is different.  My MasterDb database and ClientDb database both have asp.net membership tables in them and I added an additional table to each I called "custom_UserInfo".  The structure of each of these tables is different and it caused errors about that table not belonging to the current context.  Renaming one of them fixed the problem.  It appears to be a problem with Type creation as these tables show up as MyApplication.Tablename, there for I think it was basically a type mismatch if you will.
0
 
LVL 19

Expert Comment

by:Amandeep Singh Bhullar
ID: 38826152
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Suggested Courses
Course of the Month13 days, 21 hours left to enroll

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question