Reputation: 35
I am trying to make the AnswerString
required to be unique among answers that share the same ModuleID
value. How would I go about achieving this?
public class Answer
{
public int AnswerID { get; set; }
[MaxLength(25)]
[Required]
[Key]
public string AnswerString { get; set; }
public int ModuleID { get; set; }
public int PictureCount { get; set; }
}
Upvotes: 2
Views: 108
Reputation: 175
I would recommend making an attribute for the property which would evaluate at the class or property level. This would apply your business logic within the object/model and not rely on EF. If your intent is not to do as such, then I recommend the attributes suggested above or applying a constraint on the table itself.
Upvotes: 0
Reputation: 3432
Add this attribute to AnswerString:
[Index("IX_AnswerStringModuleId",2,IsUnique = true)]
Then add this attribute to ModuleId:
[Index("IX_AnswerStringModuleId",1, IsUnique = true)]
Basically this sets up a unique constraint where the combo of ModuleId and AnswerString must be unique.
See this answer as well: Unique Key constraints for multiple columns in Entity Framework
Upvotes: 2