Using connection strings

Passing the database name to the context constructor is simple if that’s all you need to do, but you may want (or need) more control than that. Remember that Entity Framework is part of ADO.NET, and when you’re working the Code First, you can use a ADO.NET standard connection string that specifies everything you need.

The exact structure of your connection string depends on the database server and of course the details depend on your development and deployment environment. I’m afraid that’s outside our scope. (And frankly, outside my area of expertise. There are a lot of database servers out there that I don’t have recent experience with.) But assuming you know what your connection string needs to look like, here are some options that the DbContext constructor gives you for using it:

Image Pass it to the constructor

You can pass the connection string to the DbContext constructor using the same technique you used to pass just the database name:

Image

Image put it in app.config

Another common (and flexible technique) is to define the connection string in App.config:


<configuration>
 <connectionStrings>
  <add name="myName"
        providerName="..."
        connectionString="..." />
  </connectionStrings>
</configuration>


If the name of the connection string is the name of the DbContext class (with or without namespace qualifiers), the Entity Framework will find or use it. If you specify a different name, you can pass the name (as a String) to the constructor using the same techniques you use to pass the database name or connection string directly.

Image Create a connection

If you’re an old ADO.NET hand, you’ll be familiar with the DbConnection class. There’s a version of the constructor that accepts a standard DbConnection object and a Boolean indicating whether Entity Framework should dispose of the connection when the context is disposed:

Image
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset