且构网

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

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

更新时间:2023-02-15 17:37:57

这里的问题是您的数据库不区分大小写,但 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 并且因此您加载的 User 实体不是您的 Registration 实体的关系.因此,EF 不会修复 User1 属性,它将保持为空.在这种情况下访问 LastName 将抛出 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.