Entity Framework Mapping Entities To Specific Database Tables

I have been playing around with the Entity Framework Code First CTP 4 in ASP.NET MVC 3 for a couple of days and have come across across a need to map an entity to a specific database table.

Entity Framework Code First automatically pluralizes all entity names when it creates database tables from your domain model. However, I had an entity called Accommodation which I did not want pluralized. It wasn’t really a big deal, just really that Accommodations sounded wrong, but it gnawed at my borderline-OCD perfectionist mind until I was forced to go looking for a solution. And here it is, you simply need to change the name of the DbSet and override the OnModelCreating method like this:

 

public class AccommodationEntities : DbContext
{
    public DbSet<Accommodation> Accommodation { get; set; }
    public DbSet<Address> Addresses { get; set; }

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Accommodation>().MapSingleType().ToTable("Accommodation");
    }
}

 

While I’m on the subject of the EF Code First CTP 4, here is another thing that caught me out.

EF Code First creates a table called EdmMetadata which stores a hash of the database schema created by EF. If you change your domain model entities EF Code First will automatically re-create all the tables in the context. I mean re-create as in drop the tables first, then create new. This is fine as long as you haven’t got any data you want to keep hold of, as you get no warning that this is going to happen.

To stop EF re-creating the tables (and I suppose to bring it out of Code First mode) I dropped the EdmMetadata table and added the following to the Application_Start() method of my global.asax:

Database.SetInitializer<AccommodationEntities>(null);

This seems to have done the trick!

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)