I want to set the default collation for a database, when Entity Framework Code First creates it.
I've tried the following:
public class TestInitializer<T> : DropCreateDatabaseAlways<T> where T: DbContext
{
protected override void Seed(T context)
{
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] COLLATE Latin1_General_CI_AS");
context.Database.ExecuteSqlCommand("ALTER DATABASE [Test] SET MULTI_USER");
}
}
This appears to run OK when SQL Server is already set to the same default collation Latin1_General_CI_AS.
But if I specify a different collation, say SQL_Latin1_General_CP1_CI_AS this fails with the error,
System.Data.SqlClient.SqlException: Resetting the connection results in a different
state than the initial login. The login fails.
Can anyone advise how I can set the collation please?
9条答案
按热度按时间aurhwmvo1#
Solution with a command interceptor
It is definitely possible, though it's a bit of a hack. You can alter the CREATE DATABASE command with a command interceptor. Il will intercept all the commands sent to the database, recognize the database creation command based on a regex expression, and alter the command text with your collation.
Before database creation
The interceptor
Remarks
Since the database is created with the right collation from the start, all the columns will automatically inherit that collation and you wan't have to ALTER them afterwards.
Be aware that it will impact any later database creation occurring inside the application domain. So you might want to remove the interceptor after the database is created.
disho6za2#
I was able to change collation with a custom migration (EF6). I have automatic migrations enabled. You need to delete your DB first.
Add-Migration [YourCustomMigration]
in Package Manager Console. (Code First Migrations)ALTER DATABASE
code BEFORE the table creation codes so they are created using the database collation you want. Also, note thesuppressTransaction
flag:public override void Up() { Sql("ALTER DATABASE [YourDB] COLLATE [YourCollation]", suppressTransaction: true); [...Your DB Objects Creation codes here...] }
Each
update-database
command issued from then on creates a new migration class. All migration codes are executed in order.qyyhg6bp3#
My solution with EFCore****2.1 was to derive from the SqlServerMigrationsSqlGenerator and override Generate(SqlServerCreateDatabaseOperation, IModel, MigrationCommandListBuilder)
then used it in the DbContext by replacing the IMigrationsSqlGenerator service
ajsxfq5m4#
I have had the same problem a while ago. Possible solutions:
Seed()
method but you can change the collation of individual columns for a table (NOTE: there is no such thing as table collation, it does relate to column in a table). You will have to change each column's collation separately.Up()
method.As you are using the
Seed()
method, I would suggest the following (modify as appropriate) within theSeed()
method:Hope that helps.
2jcobegt5#
I would like to explain why you should not use the seed method for this. If you change your database collation after any columns have been added there is a large risk for
collation conflicts
like belowCannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_100_CI_AS" in the equal to operation.
This is due to the fact that if you alter your database with
ALTER DATABASE [YourDb] COLLATE [YourCollation]
you will only change the databases collation and not previously created columns.Example in T-SQL:
Due to this you need to change database collation before any columns are added or change every column separately. Possible solutions:
I would put the
DbInterception.Add
in a class deriving fromDbConfiguration
or inApplication_Start
inGlobal.asax
as recommended in the documentation. Note:Wherever you put this code, be careful not to execute DbInterception.Add for the same interceptor more than once, or you'll get additional interceptor instances.
I would also not inherit from the interface but instead use the implementation of
DbCommandInterceptor
as Microsoft does in their examples.More information here: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/connection-resiliency-and-command-interception-with-the-entity-framework-in-an-asp-net-mvc-application
Resetting the connection results in a different state than the initial login
will be thrown.Your Seed SqlException can be solved by using a plain ADO.Net connection, so the context's connection won't be reset. However as mentioned above this will probably cause a lot of errors later.
SqlException: Resetting the connection results in a different state than the initial login. The login fails. Login failed for user ''. Cannot continue the execution because the session is in the kill state.
Source:
https://stackoverflow.com/a/50400609/3850405
hlswsv356#
It's simply not possible using current versions of EF (EF6). However, at least EF6+ can now work with already existent database. We've changed our deployment scenario such that the database is already created by our deployment script (incl. the default collation) and let EF6 work with the existing database (using the correct default collation).
If you absolutely have to create the database inside your code and cannot use anything else than EF (e.g. you are not able to create the database using ADO.NET) then you have to go for seliosalex answer. It's the only solution we came up, however, see my comment, it is a lot of work to do it right.
9rygscc17#
EF 5 now supports creating missing tables in an existing database with Code First, so you can create an empty database and set the collation correct, before running an CF on it.
ndh0cuux8#
aamkag619#
I wasn't happy with all the workarounds, so tried and tested this with EF Core 7:
...}
It worked.