为什么ef6不创建包含外键列的多个列索引?

时间:2016-01-25 09:16:28

标签: entity-framework-6 entity ef-migrations

ENTITY

public class UrbanRenewalPoint
{
    public int Id { get; set; }
    public int UrbanRenewalId { get; set; }
    public virtual UrbanRenewal UrbanRenewal { get; set; }
    public int Order { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

CONFUGURATION

public class UrbanRenewalPointConfiguration : EntityTypeConfiguration<UrbanRenewalPoint>
{
    public UrbanRenewalPointConfiguration()
    {
        HasKey(p => p.Id);
        HasRequired(p => p.UrbanRenewal).WithMany(p => p.UrbanRenewalPoints).HasForeignKey(p => p.UrbanRenewalId);
        Property(p => p.UrbanRenewalId).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("PointOrder", 1) { IsUnique = true }));
        Property(p => p.Order).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("PointOrder", 2) { IsUnique = true })).IsRequired();
        Property(p => p.Latitude).IsRequired();
        Property(p => p.Longitude).IsRequired();
    }
}

初始移民

        CreateTable(
            "dbo.UrbanRenewalPoint",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    UrbanRenewalId = c.Int(nullable: false),
                    Order = c.Int(nullable: false),
                    Latitude = c.Double(nullable: false),
                    Longitude = c.Double(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.UrbanRenewal", t => t.UrbanRenewalId)
            .Index(t => t.UrbanRenewalId);

所以我不明白为什么迁移没有我的PointOrder索引的代码?有没有其他方法可以用流畅的api来成功?

PS:我在设置配置时无法使用UrbanRenewal属性,因为我发现错误(T不能为空)因为我使用UrbanRenewalId。现在我不喜欢它,但我手动将我的索引添加到自动生成的迁移文件中;

.Index(t =&gt; new {t.UrbanRenewalId,t.Order},unique:true,name:&#34; PointOrder&#34;)

1 个答案:

答案 0 :(得分:0)

无论创建索引的类型,您都需要将ARRAY列传递到索引表达式

实施例

CreateTable("dbo.SomeTable", c => new
{
   MyKey = c.Long(nullable: false, identity: true),
   Key = c.String(nullable: false, maxLength: 100),
   Value = c.String(nullable: false, storeType: "xml")
})
.PrimaryKey(t => t.MyKey, name: "PK_dbo_SomeTable");
.Index(t => new { t.Key, t.Value }, unique: false, name: "IX_dbo_SomeTable");

请记住,这只是在数据库中创建索引。您仍然需要将ATTRIBUTE添加到模型中以用于EF自身的恶意目的; - )。

实施例

[Table("dbo.SomeTable")]
public partial class SomeTable
{
    [Key]
    public long MyKey { get; set; }

    [Required]
    [StringLength(100)]
    [Index("IX_dbo_SomeTable", IsUnique = true, Order = 1)]
    public string Key { get; set; }

    [Column(TypeName = "xml")]
    [Required]
    [Index("IX_dbo_SomeTable", IsUnique = true, Order = 2)]
    public string Value { get; set; }
}