如何在Entity Framework中处理可空的外键字段? [英] How to handle a nullable foreign key field in Entity Framework?
问题描述
SQL Server可以使用可空的外部钥匙,所以我想保持支票约束到位。我的选择在这里?
提前感谢
EF 支持可空的int。但int和int?是两种不同的类型。针对一个可空的int列生成一个新的模型,你会看到。
更新模型的原因并没有改变关联的多重性,因为EF更新时会尝试保留CSDL自定义。它将从头开始重新生成SSDL,并向CSDL添加任何新对象/关系,但不会覆盖您可能已经进行的更改。
I have a table with a nullable integer field that is a foreign key. When I try to set the entity model's Nullable property to True I get an error that states that fields of type Int32 can not be null. So if Entity Framework doesn't support nullable integers, how can I insert rows into the table with a null value? If no value is specified for the nullable property Entity Framework inserts a value of 0 which throws an error because of the foreign key constraint.
SQL Server is fine with a nullable foreign key so I'd like to keep the check constraint in place. What are my options here?
Thanks in advance!
EF does support a nullable int. But int and int? are two different types. Generate a new model against a nullable int column and you'll see.
The reason that updating your model didn't change the multiplicity of the association is that the EF tries to preserve your CSDL customizations when you update. It will regenerate SSDL mostly from scratch, and add to the CSDL any new objects/relationships, but it doesn't overwrite changes you might have made.
这篇关于如何在Entity Framework中处理可空的外键字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!