Entity Framework nvarchar Case Sensitivity on Foreign key

前端 未结 2 1739
迷失自我
迷失自我 2021-01-05 04:20

I have fairly simple table structure as below and issue sounds strange to me. Though I have chosen to work around it but would like to take experts opinion.

I have t

2条回答
  •  青春惊慌失措
    2021-01-05 05:07

    The problem here is that your database is case insensitive but CLR (.NET) is not and in contrast to database it cannot be switched to case insensitive mode globally - you must do it per comparison.

    When you call item.User1.LastName EF will trigger lazy loading - additional query is executed in the database to load a related user but when the user is materialized EF will start fixing and validating its relational model and here comes the problem - it compares strings with case sensitivity so according to this setting a is not equal to A and because of that your loaded User entity is not relation of your Registration entity. As a result EF will not fix up User1 property and it will remain null. Accessing LastName in such case will throw NullReferenceException.

    There are only two solutions:

    • Fix your database and make sure that this case difference will not appear in your data again
    • If you are at the beginning of the project or if you have full control over the database redesign it. NVarChar primary keys and foreign keys are bad database design.

    If neither of those choices is applicable for you, you should avoid using EF with such database.

提交回复
热议问题