Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Configure Schema Per Entity

In LINQ to SQL there is a very simple convention to tell the mapper what database schema to use - [Table(Name = "SchemaName.TableName")].

Is there something similar in EF CF 4.1? I would rather not use annotations in the entity classes to keep them as pure as possible. For the sake of keeping my project moving I'll make the sacrifice though.

This question is close, but not exactly what I need. It may even be outdated as it looks like it's referring to classes that have been renamed or have had breaking changes since the recent EF 4.1 release - Entity Framework 4: Code First - Creating db in another schema? MapSingleType?

EDIT: I should also mention that my application has three schemas at the moment, so I can't necessarily use a solution that changes only the default schema from "dbo" to "otherschema".

like image 635
Yuck Avatar asked May 11 '11 12:05

Yuck


1 Answers

The linked answer is old and it doesn't work because custom conventions were removed from final version. If you want to change name of schema you can use fluent api:

public class Context : DbContext
{
    public DbSet<YourType> YourTypeSet { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<YourType>().ToTable("TableName", "SchemaName");
    }
}
like image 101
Ladislav Mrnka Avatar answered Oct 08 '22 22:10

Ladislav Mrnka