Entity Framework Code First with SQL Server

As you know EF 4.1 Code First can create tables out of the model classes. If connection string is not provided in the config file, EF looks for local Sql express instance. If available, it connects to the instance and creates Database with table names same as your model classes.

But, what if you have a local SQL server instance instead of SQLExpress or your instance name is not SQLExpress? EF won’t connect automatically to the Instance in either of these cases,unless you explicitly provide your connection string.  How can you use the local SQL Instance without specifiying the connection string?

It is possible. Here is where we need to see what exactly EF looks for connecting to a SQL instance. To be precise EF looks for .\SQLExpress instance  in your local system. To make EF connect to any SQL instance just create an alias named “.\SQLExpress” for your SQL Instance. This can be done via SQL Server Configuration Manager tool as shown below.

Now EF connects to the SQL instance just fine as if it were local .\SQLExpress instance.

About these ads

4 Comments on “Entity Framework Code First with SQL Server”

  1. balajesankar says:

    For providing connection string for sql server or express with your own databases, check the MSDN
    blog http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

  2. Armadillo says:

    Nice tip!

  3. CCPony says:

    Doesn’t work.

  4. Andreas B. says:

    Great, it works! Wasn’t sure regarding Server name in the Alias but obviously your example covers the default instance name since it works well for me.

    For whom it doesn’t work: Probably you have to restart your SQL Servier instance in order for the Alias configuration to be in effect.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.