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
.
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.
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.
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.
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");
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With