Entity framework 4 – Code only – How-to change target names in the database table

For a couple of days ago I got the question of “my mappings doesn’t work”. I looked at it and found that the database tables were generated upfront and not by the ObjectContext. The columnnames had other names. Than how-do you solve this missmatch if you really do want to have separate namings? Using MapSingleType.

Personally, I let the context create the database and the tables, since I want the model to drive the database design.

The entity

[Serializable]
public class Car
{
    public string LicencePlate { get; set; }
    public int CountryCode { get; set; }
}

The mapping

[Serializable]
public class CarMapping : EntityConfiguration<Car>
{
    public CarMapping()
    {
        HasKey(c => new { c.CountryCode, c.LicencePlate });
        MapSingleType(c => 
            new
                {
                    TheCountryCode = c.CountryCode, 
                    TheLicencePlate = c.LicencePlate
                }).ToTable("dbo.TheCars");
    }
}

The result
Table: TheCars (you don’t have to use “ToTable”).
Columns:

  • TheCountryCode
  • TheLicencePlate

//Daniel

3 thoughts on “Entity framework 4 – Code only – How-to change target names in the database table

  1. Pingback: Entity framework 4 – CTP3 – Code first vs Linq to Sql « Daniel Wertheim

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