Oxite Administrator (gravatar)

EntityConnection code walkthrough

// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "AdventureWorks";

// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
    new SqlConnectionStringBuilder(); 1

// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;

// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();2

SqlConnectionStringBuilder class 1 is used to create the Sql Server specific connection string 2. Later this generated connection string will be passed to the EntityConnectionStringBuilder instance. This gives the following advantages

  1. Strongly typed connection string properties
  2. Support for synonyms
  3. Security
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
    new EntityConnectionStringBuilder();

//Set the provider name.
entityBuilder.Provider = providerName;3

// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;

// Set the Metadata location.
entityBuilder.Metadata = @"res://*/AdventureWorksModel.csdl|
                            res://*/AdventureWorksModel.ssdl|
                            res://*/AdventureWorksModel.msl";4
Console.WriteLine(entityBuilder.ToString());


Unlike the SqlConnectionStringBuilder, EntityConnectionStringBuilder is vendor agnostic and hence we need to specify the provider name 3 before generating the Entity connection string. Metadata file locations 4 should also be specified before constructing the connection string.

using (EntityConnection conn =
    new EntityConnection(entityBuilder.ToString()))
{
    conn.Open();
    Console.WriteLine("Just testing the connection.");
    conn.Close();
}

0 Comments

Your Information
Mrs. Gravatar (gravatar)

<-- It's a gravatar

your comment