更新时间: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的
主键和外键是坏的数据库设计。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.