2个属性中的一个应为null(EntityFramework Code First) [英] One out of 2 properties should be null (EntityFramework Code First)
问题描述
我在论坛中搜索了很多,但没有发现有关此问题的任何内容。
I've searched a lot in the forum, but haven't found anything about regarding this issue.
我在EntityFramework代码中有2个属性首先: / p>
I have 2 properties in the EntityFramework Code First:
[Column(TypeName = "Money")]
public decimal? Debit { get; set; }
[Column(TypeName = "Money")]
public decimal? Credit { get; set; }
其中一个应该不为空,但另一个应为null
示例:
One of them should be not null, but the other one should be null Examples:
Debit=null;
Credit=34;
Debit=45;
Credit=null;
另一方面,不可能同时设置两者,也不能设置为空。
可以用数据注释处理这个问题,还是应该用解决方法解决?
On the other hand, it should not be possible to set both or none of them null. Is it possible to handle this issue with data annotations or should I solve it with a workaround?
最好的问候!
推荐答案
您可以随时对数据库端进行验证,具有约束条件,
You could always do the validation on the database side with a constraint,
ALTER TABLE TableName
ADD CONSTRAINT OneColumnNull CHECK
((Debit IS NULL AND Credit IS NOT NULL) OR
(Debit IS NOT NULL AND Credit IS NULL)
)
完全符合您的要求。您可以将该查询作为数据库迁移脚本之一。
does exactly what you are looking for. You could just put that query as part of one of your database migration scripts.
这篇关于2个属性中的一个应为null(EntityFramework Code First)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!