从其他实体获取的唯一索引

本文关键字:唯一 索引 获取 其他 实体 | 更新日期: 2023-09-27 18:33:10

我有下一个类:

public class Y_Equipment
{
    [MaxLength(150)]
    public string CategoryDisplayName{get;set;}
    [MaxLength(150)]
    [Key]
    [Index("IX_Y_Equipment",2, IsUnique = true)]
    public string CategoryCode{get;set;}
    [MaxLength(150)]
    public string EquipmentDisplayName{get;set;}
    [MaxLength(150)]
    [Index("IX_Y_Equipment",3, IsUnique = true)]        
    public string EquipmentCode{get;set;}
    public Int32 Timespamp{get;set;}
    [Index("IX_Y_Equipment", 1, IsUnique = true)]
    public virtual Y_Unit Unit { get; set; }
}
public class Y_Unit : Item
{
    [DefaultValue("")]
    [MaxLength(10)]
    public string Flag { get; set; }
    [DefaultValue("")]
    [MaxLength(100)]
    public string UnitSubType { get; set; }
    [DefaultValue("")]
    [MaxLength(100)]
    public string UnitSubTypeID { get; set; }
    [DefaultValue("")]
    [MaxLength(100)]
    public string Category { get; set; }
}
public abstract class Item
{
    [MaxLength(150)]
    public string Name{get;set;}
    [Index("IX_EntityCode",1,IsUnique = true)]
    [MaxLength(15)]
    [Key]
    public string Code{get;set;}
}

我的问题是下一个:我想在Y_Equipments上有 3 个项目索引唯一键,并且该组合的 1 部分应该是外键形式 Y_Unit[code](3le 元素组合不能重复(。

即:

  • "Cat1"、"Equip1"、"Unit1",
  • "Cat1"、"装备1"、"单元 2">
  • "Cat1"、"装备2"、"单元 2">

但不是

  • 再次是"Cat1"、"装备1"、"Unit1">

但相反,我得到了类似的东西

 CreateIndex("dbo.Y_Equipment", new[] { "CategoryCode", "EquipmentCode" }, unique: true, name: "IX_Y_Equipment");
 CreateIndex("dbo.Y_Equipment", "Unit_Code");

这不是我想要的...任何提示如何正确更新我的实体?谢谢。

从其他实体获取的唯一索引

好的,今天我留下来阅读了更多关于 EF 的信息,并找到了一种方法来做到这一点。

脚本创建索引时的结果:

/****** Object:  Index [IX_Y_Equipment]    Script Date: 12/5/2014 10:26:10 PM ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Y_Equipment] ON [dbo].[YB_Equipment]
(
    [Unit_Code] ASC,
    [CategoryCode] ASC,
    [EquipmentCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

我是怎么做到的?我自己添加了外键并将其映射到索引,现在我的类如下所示:

public class Y_Equipment
{
    [MaxLength(150)]
    public string CategoryDisplayName { get; set; }
    [MaxLength(150)]
    [Key]
    [Index("IX_Y_Equipment", 2, IsUnique = true)]
    public string CategoryCode { get; set; }
    [MaxLength(150)]
    public string EquipmentDisplayName { get; set; }
    [MaxLength(150)]
    [Index("IX_Y_Equipment", 3, IsUnique = true)]
    public string EquipmentCode { get; set; }
    public Int32 Timespamp { get; set; }
    [Index("IX_Y_Equipment", 1, IsUnique = true)]
    [ForeignKey("Unit")]
    [MaxLength(15)]
    public string Unit_Code { get; set; }
    public virtual Y_Unit Unit { get; set; }
}

这正是我想要的。我想对@Colin说谢谢,因为他向我暗示了如何做到这一点。