我使用Entity Framework(软件包6.2.0)代码优先,并尝试在两个都是外键的字段上创建唯一索引。与其创建1个唯一索引,不如生成两个单独的索引。在我的实体下方:
public class EntityA
{
// PK identity
public int Id { get; set; }
// Using unique index as alternative to Alternate key
[MaxLength(16)]
[Index(IsUnique = true)]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<LinkedEntities> LinkedEntities { get; set; }
}
public class EntityB
{
// PK identity
public int Id { get; set; }
// Using unique index as alternative to Alternate key
[MaxLength(16)]
[Index(IsUnique = true)]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<LinkedEntities> LinkedEntities { get; set; }
}
public class LinkedEntities
{
// PK identity
public int Id { get; set; }
// Using unique index on combination of A and B as alternative to Alternate key
[Index("IX_UniqueLinkedEntities", IsUnique = true, Order = 1)]
public EntityA EntityA { get; set; }
[Index("IX_UniqueLinkedEntities", IsUnique = true, Order = 2)]
public EntityB EntityB { get; set; }
}
以下是为这些实体生成的迁移脚本的输出:
public override void Up()
{
CreateTable(
"dbo.EntityA",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 16),
Description = c.String(),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true);
CreateTable(
"dbo.LinkedEntities",
c => new
{
Id = c.Int(nullable: false, identity: true),
EntityA_Id = c.Int(),
EntityB_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.EntityA", t => t.EntityA_Id)
.ForeignKey("dbo.EntityB", t => t.EntityB_Id)
.Index(t => t.EntityA_Id)
.Index(t => t.EntityB_Id);
CreateTable(
"dbo.EntityB",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 16),
Description = c.String(),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true);
}
一旦执行了迁移脚本,我就会在数据库的LinkedEntities表上看到3个索引:
为什么EF不能在EntityA和EntityB两个字段的组合上创建唯一索引“ IX_UniqueLinkedEntities”?我觉得这与两个字段都是FK有关。
在这种情况下,创建我唯一约束的唯一方法是按照建议here进行操作吗?还是自己在迁移脚本中包含原始SQL DDL?