Define SQL table primary key as case sensitive using Entity Framework Code First

夙愿已清 提交于 2019-12-06 13:31:08

So far the best solution I got (and by no means I consider it a good one), is to generate the sql script using EF, and then modifying it there.

The reason I'm doing it is because the value I'm changing is not only a primary key it is also involved in 3 other constraints.

In case anyone else is experiencing the same and just need a workaround, you can do the following:

Save the sql script to a new query:

Update-Database -Script -SourceMigration:0

Then instead of dropping and adding many constraints just locate the row that defines the primary key which you like to make as case sensitive, in my case:

[Lbl] [nvarchar](128) NOT NULL

change to:

[Lbl] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL

Before you go and run your script, make sure to add the COLLATE SQL_Latin1_General_CP1_CS_AS when using this as a foreign key in other tables.

I don't like this solution, but I'm only using it since it's all I got. If you have a better solution please post it!

Solution 2

I can confirm this works as well, it is a bit of an over kill. you define your own data annotation, here we define a custom [CaseSensitive]. Works really nice, but again it really feels like to much... if I didn't had many db migration I would stick to my first suggestion.

Entity Framework doesn't have anything built in to do this - it will always create your database and columns using the default collation. However, you can manually run some SQL in a migration Up() method to modify the collation of a specific column:

Sql("ALTER TABLE yourTable ALTER COLUMN YourColumn VARCHAR(50) COLLATE Latin1_General_CS_AS");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!