唯一索引来自其他实体

时间:2014-12-04 13:44:05

标签: c# entity-framework orm

我有下一个课程:

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元素组合不能重复)。

IE:

  • ' CAT1'' Equip1'' 1单元',
  • ' CAT1'' Equip1'' UNIT2'
  • ' CAT1'' Equip2'' UNIT2'

但不是

  • ' CAT1'' Equip1'' 1单元'再次

但我得到像

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

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

1 个答案:

答案 0 :(得分:0)

确定, 今天我留下来阅读更多有关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说谢谢,因为他给我一个提示如何做到这一点。