开发者

How to handle a nullable foreign key field in Entity Framework?

开发者 https://www.devze.com 2023-01-12 20:04 出处:网络
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

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 Framew开发者_开发知识库ork 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号