I'm porting my EF to EF Core. There doesn't appear to be a HasDefaultSchema method in the new API. What is the equivalent of this code EF Core?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Notifications");
}
There are 2 ways to change the schema, either by applying the TableAttribute or by implementing the interface IEntityTypeConfiguration<TEntity> . The first option won't help us because the schema is hard-coded. The second option gives us the ability to provide the schema from DbContext to the EF model configuration.
Map Entity to Table. Code-First will create the database tables with the name of DbSet properties in the context class, Students and Standards in this case. You can override this convention and give a different table name than the DbSet properties, as shown below.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
It's exactly the same as the sample code.
The only difference with EF6 is that as most of the EF Core fluent (and not only) method it's implemented as extension method (rather than instance method) of the ModelBuilder
class inside the RelationalModelBuilderExtensions
class.
In order to use it, make sure you reference the Microsoft.EntityFrameworkCore.Relational nuget, and have using Microsoft.EntityFrameworkCore;
I am using SQL Server as the Database, so in this case I had to
Microsoft.EntityFrameworkCore
and Microsoft.EntityFrameworkCore.SqlServer
packages, and,using Microsoft.EntityFrameworkCore;
Note, only installing Microsoft.EntityFrameworkCore
will complain that 'HasDefaultSchema ' is undefined, and also VS would not provide any suggestion to install the other package.
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