Creating Entity Connection in Linq To Entities ( Entity Framework)

there are key scenarios in which you want to create your connection string at runtime (dynamically), instead of old Connectionstring entity framework uses "EntityConnection" string

now how one will proceed if he wants to create EntityConnection at runtime say read from configuration and then use it or in case of DDR (data dependent routing)  here is the solution that will save you from this trouble.

  • Create Instance of EntityConnectionStringBuilder
  • Assign it the "SQL Connection String"
  • provide the meta data
  • Assign the provider name
  • then all you have to request EntityConnectionStringBuilder to return value from ToString();
  • and you are good to go 🙂
   1: EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
   2: entityBuilder.ProviderConnectionString = connectionstring;
   3: entityBuilder.Metadata = "res://*/";
   4: entityBuilder.Provider = "System.Data.SqlClient";
   5: return entityBuilder.ToString();

kick it on  Shout it

  1. #1 by David Navarro on November 11, 2011 - 4:56 am

    Thanks for posting this information. I have a couple of questions; with my Silverlight 4, WCF RIA app, can I set a connection string when the user logs into the app and have the connection remain in tact until the user logs out again?

    Or, do I have to continuoulsy set it as the app makes database calls?

    Please let me know and thanks!

    ~ Dave

    • #2 by Usman Masood on February 22, 2012 - 9:16 am

      Sorry for delayed reply as i was out of touch 🙂
      i know you have figured out already but here is the deal:
      In case of databases i am in big favour of open connection for short interval of time. if connection string remains same .net connection management places it in pool and next time when a connection is opend or requested it avoids overheads.
      So if you want to hold entity connection string (after ist generation) that would be fine, but don’t hold the connection.

  2. #3 by Mark J on October 22, 2010 - 4:48 pm

    Thanks for this… me out of big time trouble 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: