第一个带有约束的代码一对多关系

问题描述 投票:0回答:1

我首先通过代码生成了以下一对多数据库结构。可以将许多按钮添加回单个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; }
  }
entity-framework asp.net-core ef-code-first
1个回答
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。我认为配置起来更容易。

© www.soinside.com 2019 - 2024. All rights reserved.