且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架nvarchar的区分大小写的外键

更新时间:2023-02-15 17:59:07

这里的问题是,你的数据库不区分大小写,但CLR(.NET)是不是和对比数据库中不能切换到全球范围内不区分大小写模式 - 你必须按照比较去做。

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.

当你调用 item.User1.LastName EF将触发延迟加载 - 额外的查询在数据库中执行加载相关用户,但是当用户物化EF会开始修复并验证其关系模型,并在此问题来了 - 它比较字符串与大小写因此按照这个设置 A 不等于 A 键,因为你装用户实体是不是你的注册实体的关系。因此EF不会修复了用户1 属性,它会保持为空。访问名字在这种情况下会抛出的NullReferenceException

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.

有只有两种解决方法:

  • 修正你的数据库,并确保这种情况下差异不会再次出现在您的数据
  • 如果你在项目的开始,或者你可以完全控制数据库的重新设计。 nvarchar的主键和外键是坏的数据库设计。
  • 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.

如果没有这些选择适用于你,你应该避免使用EF这样的数据库。

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