Database-First connection string

by Sachin Singh

Posted on Sunday, 03 January 2021

Tags: Connection String in database-First Approach connection string in detail

Different application may point to a different database on the different or same server, due to this we need something in our application which ensures to connect to the right database, something which will tell Entity Framework to connect to which sever and which database, this is where connection string comes into the picture and gives all the necessary information to Entity Framework like server name, database name, and credentials required to connect to the database.

Let's first discuss the connection string , a normal connection string has following parts :
    • Data Source : which specifies the server name where our database resides.
    • Initial Catalog : which specifies the database name
    • Integrated Security or UserName and Password, depending upon whether we are using windows authentication or SQL Server Authentication.

In the previous article we build our domain Model using Database-First workflow , now let's take a look to the connection string that EF has generated into our AppConfig File, if you have created a web Application then look inside your webconfig file.

    <add name="OrganizationDbContext" connectionString="metadata=res://*/OrganizationModel.csdl|res://*/OrganizationModel.ssdl|res://*/OrganizationModel.msl;provider=System.Data.SqlClient;provider connection string="
      data source=SACHIN-PC\SQLEXPRESS;initial catalog=Test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 
         providerName="System.Data.EntityClient" />

The connection string that EF generates ,looks weird and Messy , it includes one extra property that is metadata which really increases its length . so what is this metadata for?

In the previous article we have seen that EDMX is based on XML which includes following 3 sections
  1. Storage Model : which contains the information about our database.
  2. Conceptual Model : which contains the information about Entities.
  3. Mappings: which describes how the database tables and Entities map to each other.

When we compile our application, the Visual Studio takes that XML and breaks it into 3 parts, and store them as resources in the assembly. The metadata that you see in the connection string points to those resources in the assembly that represents our Storage Model, Conceptual Model, and the Mappings between the two. We can't open the assembly and check this, this was just for anybody who wanted to know why does the connection string generated by EF looks like this and what does it signify.