使用约束编写第一个一对多关系

时间:2019-12-16 16:49:47

标签: entity-framework asp.net-core ef-code-first

我首先通过代码生成了以下一对多数据库结构。可以将许多按钮添加回单个GSMUnit的关系中。 BtnNo应该是唯一的(对于每个GSMUnitId),并且不应重复。目前可以复制。我该如何预防?

  public class GSMUnit
  {
        public int Id { get; set; }
        [MaxLength(20)]
        public string Model { get; set; }
        [MaxLength(40)]
        public string GsmName { get; set; }
        [MaxLength(40)]
        public string TelephoneNum { get; set; }
        public int GSMSiteId { get; set; }
        public virtual GSMSite GSMSite { get; set; }
        public virtual GSMSetting GSMSettings { get; set; }
        public virtual ICollection<Button> Buttons { get; set; }
  }

  public class Button
  {
        public int Id { get; set; }
        [MaxLength(30)]
        public string Primary { get; set; }
        [MaxLength(30)]
        public string Divert1 { get; set; }
        [MaxLength(30)]
        public string Divert2 { get; set; }
        [MaxLength(30)]
        public string Divert3 { get; set; }
        [MaxLength(20)]
        public string AptNo { get; set; }
        [MaxLength(10)]
        public string Code { get; set; }
        [MaxLength(4)]
        public string DTO { get; set; }
        [MaxLength(4)]
        public string Timeband { get; set; }
        [MaxLength(15)]
        public string BtnNo { get; set; }
        [MaxLength(20)]
        public string AptName { get; set; }
        public int GSMUnitId { get; set; }
        public virtual GSMUnit GSMUnit { get; set; }
  }

1 个答案:

答案 0 :(得分:0)

您可以使用Index属性:

  public class Button
  {
        public int Id { get; set; }
        [MaxLength(30)]
        public string Primary { get; set; }
        [MaxLength(30)]
        public string Divert1 { get; set; }
        [MaxLength(30)]
        public string Divert2 { get; set; }
        [MaxLength(30)]
        public string Divert3 { get; set; }
        [MaxLength(20)]
        public string AptNo { get; set; }
        [MaxLength(10)]
        public string Code { get; set; }
        [MaxLength(4)]
        public string DTO { get; set; }
        [MaxLength(4)]
        public string Timeband { get; set; }
        [MaxLength(15)]
        public string BtnNo { get; set; }
        [MaxLength(20)]
        public string AptName { get; set; }

        [Index(IsUnique = true)]
        public int GSMUnitId { get; set; }
        public virtual GSMUnit GSMUnit { get; set; }
  }

但是我建议您看一下Fluent API。我认为配置起来更容易。