0
class Entity
{
     public int Id { get; set; } // PK
     public string Val1 { get; set; } 
     public string Val2 { get; set; } 
}

My Desire/Constraint that I want to add - When inserting a new row to the table, one of the Val columns must be set.

In other words, you can set both OR one of them BUT neither of them is not an option.

This is the same question asked in SQL but in my case, I want to do it in EF Code first approach.

Any Possible Data annotations Attribute that can be used to achieve this ?

Or any special method that I can find in ModelBuilder ?

ASD_ASD
  • 21
  • 1
  • 4
  • Which version of Entity Framework? In EF Core 3.x, [HasCheckConstraint](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationalentitytypebuilderextensions.hascheckconstraint?view=efcore-3.1) method could be your friend. – Tor Apr 16 '20 at 15:45
  • I have EF Core 2.1, but this doesn't exactly give me the answer I desire. From the example I saw [at this link](https://stackoverflow.com/a/60199728/7411908), it seems that I'll need to use SQL code which ultimately defeats the whole point of writing it in "C# style". But it's a nice solution thou – ASD_ASD Apr 20 '20 at 13:12
  • Ahh, this marked as duplicate, but I was curious, and I tried something for you. But in a nutshell: you can create some attribute, which can mark properties as a check constraint (at least one of them should be not null). And you have to write your magic logic in the `OnModelCreating` method (gets all `DbSet`, collect the properties which has your attribute, and write the check constraint scripts). Then, your job is just mark the entity properties with your attribute. Works like a charm :) – Tor Apr 20 '20 at 20:02

0 Answers0