108

I have an Entity and I am to configure Entity Framework to map it to a database table with different name.

I can easily do this with Code First DataAnnotations (DataAnnotations.Schema.TableAttribute).

But due to limitations now I have to use Code First Fluent API (my domain objects will be used by external clients, so they shouldn't be technology-specific - e.g. have any references to DataAnnotations)

I've searched on MSDN but found nothing. So is it possible and how?

Thank you.

Stephen Hosking
  • 1,405
  • 16
  • 34
bairog
  • 3,143
  • 6
  • 36
  • 54
  • In general you should create DTO's (data transfer objects) and map your EF objects to them, you should never use the EF classes directly unless you're working on a small/trivial app. – reggaeguitar Feb 24 '16 at 23:08

3 Answers3

240

You can also use the Table annotation:

[Table("InternalBlogs")]
public class Blog

See: Code First Data Annotations

Assaf S.
  • 4,676
  • 2
  • 22
  • 18
124

You'll use the .ToTable() method:

modelBuilder.Entity<Department>().ToTable("t_Department");   

Source: MSDN: http://msdn.microsoft.com/en-us/data/jj591617.aspx

Jack Allen
  • 549
  • 2
  • 5
  • 19
Martin Cron
  • 1,154
  • 1
  • 8
  • 10
  • 1
    i prefer this because i want all anotations in one place – rajeemcariazo Mar 20 '16 at 10:49
  • it there any validation that the table exists? we renamed a table and nothing broke, is this the behavior you'd expect? it obviously can't do CRUD on the renamed table, but it doesn't seem to break anything... – AZ Chad May 11 '16 at 21:12
11

Use ToTable method:

public class MyEntityMap : EntityTypeConfiguration<MyEntity>
{
    public const string TableName = "MyEntity";

    public MyEntityMap()
    {                   
        ToTable(TableName);

        Property(t => t.Id);
    }
}
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • 1
    I think breaking out your mappings into classes is the cleanest approach. – SventoryMang Sep 06 '16 at 18:24
  • 3
    But then in your `OnModelCreating` method you have to do: `modelBuilder.Configurations.Add(new MyEntityMap());` where instead of you could have just added a `modelBuilder.Entity().ToTable("MyEntityTable");` so no, this is not the cleaner way unless you also had other mapping to do for this entity. – Serj Sagan May 22 '17 at 20:22