2

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; }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I am assuming you're using a database, and if so, Can you just check for the occurence of that value in the DB? `var item = context.Model.Where(x => x.ModuleID == SomeModuleID && x.AnswerString == someAnswerString).ToList(); if(item.Count > 0) { /* item exists */ }` – Ingenioushax Jul 13 '16 at 19:05

2 Answers2

2

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

Community
  • 1
  • 1
Ryan Bennett
  • 3,404
  • 19
  • 32
0

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.

Anthony Mason
  • 165
  • 1
  • 12