112

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.

1
  • 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. Commented Feb 24, 2016 at 23:08

3 Answers 3

248

You can also use the Table annotation:

[Table("InternalBlogs")]
public class Blog

See: Code First Data Annotations

Sign up to request clarification or add additional context in comments.

5 Comments

Thx, but if you carefully read my question - you'll see that apptoach directly in the middle of it :)
Even though the annotation is named "Table", it appears to work fine for views as well as for tables.
@JonSchneider I'm just arguing definitions here for no reason in particular, but a view is a read-only table.
The Table annotation resides in System.ComponentModel.DataAnnotations.Schema;.
How has this got more upvotes, the question clearly asks for the fluent api version
135

You'll use the .ToTable() method:

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

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

2 Comments

i prefer this because i want all anotations in one place
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...
12

Use ToTable method:

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

    public MyEntityMap()
    {                   
        ToTable(TableName);

        Property(t => t.Id);
    }
}

2 Comments

I think breaking out your mappings into classes is the cleanest approach.
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<MyEntity>().ToTable("MyEntityTable"); so no, this is not the cleaner way unless you also had other mapping to do for this entity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.