Reputation: 7592
How can I specify the collation of a column, a table, or a database by using annotation or Fluent API? I know there are some clean ways for MySql Provider. However, I couldn't find any way for SQL Server other than executing a raw SQL command.
Upvotes: 13
Views: 7164
Reputation: 161
UseCollation() for database and column levels was added to EF Core 5.
Upvotes: 4
Reputation: 522
Although it is possible to change the collation of the database after creation (while there are some data in its tables), it is better to set the collation of the database before creating any tables. So in EF core for creating database initially before creating any table:
PM> add-migration CreateDatabase
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
migrationBuilder.AlterDatabase("CollationName");
//or
migrationBuilder.Sql("EXEC('ALTER DATABASE [POMADB] COLLATE CollationName ');", suppressTransaction: true);
PM> update-database
I have tested this code in .NET Core 5, Visual Studio 2019, Ef core 5.0.9
For further information look at this link Ability to specify database collation
Upvotes: 1
Reputation: 5183
Looks like it will not be done at all:
Here is the closed Issue in aspnet/EntityFrameworkCore: CodeFirst: Set column collation
We discussed and concluded that setting different collations per column isn't a very common requirement and it's probably not something we would make first class in EF. This would be a good candidate for using annotations to define additional metadata and then extending our SQL generators to process those and specify collation.
The only solution seems to be this one: Entity Framework Code First - Change Table Column Collation
... you can create custom database initializer and execute ALTER TABLE command.
Upvotes: 2