Free Web Development Online Tutorials, Learn to Code
Learn Entity Framework with C#, Entity Framework Core, Code First, DB First Approach

Database Connection in Entity Framework C#

EF Encrypted connection string

Here you learn how to set up database connection information in entity framework connection string builder.

In DbContext constructor you can simply pass your connection string, but that may look dirty and will be difficult to maintain when any changes required in future.

So, we create a separate class with static string property

Entity Connection StringBuilder setup

Note: In case you have encrypted username and password or other information, you can decrypt them before setting up into Entity Connection String Builder object.

This is how you can set create a property to setup connection details, provider and metadata information, read the code here.

Decrypt an encrypted string value in EF
entity framework databse connection setup
Connection String Builder in EntityFramework

If you are not sure about what .csdl .ssdl file names are! Check your edmx file

Here is the Code for SqlConnectionStringBuilder setup
public static string EFConnectionString            
        SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
        providerCs.InitialCatalog = ConfigurationManager.AppSettings["DatabaseName"];
        providerCs.UserID = ConfigurationManager.AppSettings["UserId"];
        providerCs.Password = ConfigurationManager.AppSettings["Password"];
        providerCs.DataSource = ConfigurationManager.AppSettings["ServerName"];
        //providerCs.UserID = CryptoService2.Decrypt(ConfigurationManager.AppSettings["UserId"]);
        providerCs.MultipleActiveResultSets = true;
        providerCs.TrustServerCertificate = false;
        EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
        ecsb.Provider = "System.Data.SqlClient";
        ecsb.ProviderConnectionString = providerCs.ToString();
        ecsb.Metadata = string.Format("res://{0}/EDModel.csdl|res://{0}/EDModel.ssdl|res://{0}/EDModel.msl", typeof(Entities).Assembly.FullName);
        return ecsb.ToString();

In case you want to use encrypted connection string, in above property you can decrypt the value retrieved from configuration file, also if you want to connection string without encryption then simply remove the decryption methods, in short this will be easy way to create connection string in entity framework

entity framework connection string builder