Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 - Code First: table schema from classes' namespace

Does any know if one can set the table schema of code first classes based on the classes' namespace?

For example, every class in namespace Core.Foo would have a schema of Foo.

like image 306
Robbie Avatar asked Mar 18 '15 18:03

Robbie


People also ask

How do I create a schema in Entity Framework Code First?

As with any code-first schema customization, you can do this by using the entity classes' attributes or through the DbModelBuilder API. With data annotations, you can use the optional second parameter of the Table attribute to specify the schema name. The code in Figure 3 implements this change in the model.

How do you use code first when an existing database schema?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.

How do I change from code first to database first?

There is no way to convert your code-first classes into database-first classes. Creating the model from the database will create a whole new set of classes, regardless of the presence of your code-first classes. However, you might not want to delete your code-first classes right away.


1 Answers

Well, you could specify the schema name using one of these two options:

  • Using Data Annotations:

    [Table("TableName","Foo")]
    public class Entity
    {
    }
    
  • Using Fluent Api:

    modelBuilder.Entity<Entity>().ToTable("TableName", "Foo");
    

Update

Digging more in this subject, I think what you looking for is a Custom Convention of EF:

public class CustomSchemaConvention : Convention
{
    public CustomSchemaConvention()
    {
        Types().Configure(c => c.ToTable(c.ClrType.Name, c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1)));
    }
}

Then, in your context, you need to override the OnModelCreating method to add the new convention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new CustomSchemaConvention());
}
like image 199
octavioccl Avatar answered Oct 23 '22 03:10

octavioccl