Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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; }

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?

Best regards!

like image 401
ComFreakDomi Avatar asked Feb 12 '23 20:02

ComFreakDomi


1 Answers

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.

like image 95
Scott Chamberlain Avatar answered Apr 07 '23 13:04

Scott Chamberlain