要求 Entity Framework 中具有共同 属性 值的项目的唯一值
Requiring Unique Values in Entity Framework among items that share a common property value
我试图让 AnswerString
要求在共享相同 ModuleID
值的答案中是唯一的。我将如何实现这一目标?
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; }
}
将此属性添加到 AnswerString:
[Index("IX_AnswerStringModuleId",2,IsUnique = true)]
然后将此属性添加到 ModuleId:
[Index("IX_AnswerStringModuleId",1, IsUnique = true)]
基本上这设置了一个唯一约束,其中 ModuleId 和 AnswerString 的组合必须是唯一的。
也看到这个答案:Unique Key constraints for multiple columns in Entity Framework
我建议为 属性 创建一个属性,该属性将在 class 或 属性 级别进行评估。这将在 object/model 中应用您的业务逻辑,而不依赖于 EF。如果您不打算这样做,那么我建议使用上面建议的属性或对 table 本身应用约束。
我试图让 AnswerString
要求在共享相同 ModuleID
值的答案中是唯一的。我将如何实现这一目标?
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; }
}
将此属性添加到 AnswerString:
[Index("IX_AnswerStringModuleId",2,IsUnique = true)]
然后将此属性添加到 ModuleId:
[Index("IX_AnswerStringModuleId",1, IsUnique = true)]
基本上这设置了一个唯一约束,其中 ModuleId 和 AnswerString 的组合必须是唯一的。
也看到这个答案:Unique Key constraints for multiple columns in Entity Framework
我建议为 属性 创建一个属性,该属性将在 class 或 属性 级别进行评估。这将在 object/model 中应用您的业务逻辑,而不依赖于 EF。如果您不打算这样做,那么我建议使用上面建议的属性或对 table 本身应用约束。