首页 > 解决方案 > 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; }
  }

标签: entity-frameworkasp.net-coreef-code-first

解决方案


您可以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。在我看来,它更容易配置。


推荐阅读