By default when Entity framework is added to a project, a file “App.config” is created if it doesn’t exists yet.
( “Web.config” in web applications).
A default connection factory that will connect to a local database is added in this file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<!-- By default, when no connection string is specified use the local database.-->
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
This factory will be used when no connection string for the specified context is found. But let clarity how EF try to find the connection string to use…
Which connection string will EF use?
To connect to the database we use a context that extend DbContext.
By default if we don’t call a DbContext base constructor, E.F. will look for a connection string name using the name of our defined context.
namespace CodeFirstAzureTest.Data
{
public class FoodContext : DbContext
{
public DbSet<Food> Foods { get; set; }
public DbSet<Recipe> Recipes { get; set; }
public DbSet<FridgeEntry> Fridge { get; set; }
}
}
It is possible to specify the name of the connection string or the complete connection string calling the base constructor:
using System.Data.Entity;
using CodeFirstAzureTest.Data.Entities;
namespace CodeFirstAzureTest.Data
{
public class FoodContext : DbContext
{
// NOTE: Call base constructor to specify the connection string name
public FoodContext() : base("name=MyFood") { }
public DbSet<Food> Foods { get; set; }
public DbSet<Recipe> Recipes { get; set; }
public DbSet<FridgeEntry> Fridge { get; set; }
}
}
When no connection string is defined, if a defaultConnectionFactory is defined, EF will use it to create a connection string using the name of the connection string he needs.
e.g. If we don’t specify the connection string name in our context and EF cannot find any connection string the factory will create one using exactly this name. This is why by default the database created locally had this name in my previous post.
Connect EF to Windows Azure
To connect to a Windows Azure we need to do the following steps:
Continue reading →
Like this:
Like Loading...