Set database collation in Entity Framework Code-First Initializer

后端 未结 8 1296
后悔当初
后悔当初 2020-12-01 12:26

I want to set the default collation for a database, when Entity Framework Code First creates it.

I\'ve tried the following:

public class TestInitiali         


        
相关标签:
8条回答
  • 2020-12-01 13:13

    I have had the same problem a while ago. Possible solutions:

    1. It appears that EF creates the database using the server default collation so one thing you could do is change that.
    2. You cannot change the database collation within the 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.
    3. If you are using migrations, you could alter the table column collations within your Up() method.

    As you are using the Seed() method, I would suggest the following (modify as appropriate) within the Seed() method:

    context.Database.ExecuteSqlCommand(
    @"ALTER TABLE MyTable ALTER COLUMN MyColumn NVARCHAR(max) COLLATE MyCollation NOT NULL");
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-01 13:14

    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.

    0 讨论(0)
提交回复
热议问题