C# – Entity Framework on .mdf file

centity-frameworksql server

I am working on some project at the moment and I have to use local database. So, I created a new service-based database (no tables atm). Then I wanted to add Entity Framework support.

Because I never used Entity Framework before, I was referring to that link: http://msdn.microsoft.com/en-us/data/jj200620.aspx.

Everything is OK, but here it gets complicated. I created my DataContext class with DbSet inside it. But, when I run my unit test, table is created on Localdb (not inside my .mdf file).

What to do?

I am pretty sure, that I did choose which database to use correctly (actually did that 3 times already), but still, data tables are created on LocalDb. What I am doing wrong here?

I am complete beginner with that (been only using doctrine ORM). Otherwise I can insert data and all, it is just on the wrong database.

Best Answer

When your doing code first development in EF, you can force EF to only ever consider one connection string name.

One of the constructors (of which there are quite a few overloads) on the EF Data Context parent classes, takes a simple string.

This string is given to be the name of a connection string in the App or Web config to use.

You make the call something like this:

using System.Data.Entity;

namespace MSSQL_EFCF.Classes
{
  public class DataAccess : DbContext
  {
    public DataAccess() : base("myConnectionString")
    {}

    public DbSet<MyTableObject> MyObjects { get; set; }

  }
}

You can still put any code you need for your own start-up (Such as DB Initializer calls) inside your constructor, and all that will get called once the base call completes.

The advantage of doing things this way forces entity framework to always use the named connection string and never anything else.

The reason this catches many developers out, and why it runs off an uses localdb is deceptively simple.

The Entity Framework DbContext by default will use the name of the data context derived class as a database name, and if it can't find a suitable connection string in any config file by that name, makes the assumption that your working in development mode without a full backing data store.

In my example above, EF would examine App and/or Web.config for a connection string called "myConnectionString"

Once it makes this development decision, it knows that localdb will be present as this gets installed with the latest builds of visual studio, and so it will automatically seek out a connection and populate it with a db that follows the name of the context in which it's used.

I've previously written a blog post on the subject, which you can find here :

http://www.codeguru.com/columns/dotnet/entity-framework-code-first-simplicity.htm

NOTE: The above applies to any database that you connect with using EF, it's the connection string that decides what/where the actual data store is.