EF Migration正在为聚合PK生成第二个索引

时间:2015-09-24 12:33:00

标签: sql-server entity-framework entity-framework-6

我正在尝试为我的项目创建一个新的迁移,我只是陷入了尴尬的境地......我有我的聚合根实体:

public class Classroom : Entity, IAggregateRoot
{
    // PK
    public int ClassroomId { get; set; }

    // ....
    public virtual ClassroomStreaming Streaming { get; set; }
}

汇总:

public class ClassroomStreaming : Entity
{
    // PK
    public int ClassroomId { get; set; }
    public virtual Classroom Classroom { get; set; }

    // Fields
    public string EmbedCode { get; set; }

    // ...
}

映射是:

public class ClassroomMap : EntityTypeConfiguration<Classroom>
{
    public ClassroomMap()
    {
        this.HasKey(t => t.ClassroomId);
        this.ToTable("Classroom");
        // ....

        // One to One
        this.HasOptional(t => t.Streaming)
            .WithRequired(p => p.Classroom);
    }
}

public class ClassroomStreamingMap: EntityTypeConfiguration<ClassroomStreaming>
{
    public ClassroomStreamingMap()
    {
        // Primary Key
        this.HasKey(t => new { t.ClassroomId });

        // Table & Column Mappings
        this.ToTable("ClassroomStreaming");

        this.Property(t => t.ClassroomId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        // Relationships
        this.HasRequired(t => t.Classroom)
            .WithOptional(p => p.Streaming)
            .WillCascadeOnDelete(true);
    }
}

当我生成迁移时,我得到以下情况:它为同一列创建PK和非聚集索引:

public override void Up()
{
    CreateTable(
        "dbo.ClassroomStreaming",
        c => new
            {
                ClassroomId = c.Int(nullable: false),
                // ....
            })
        .PrimaryKey(t => t.ClassroomId)
        .ForeignKey("dbo.Classroom", t => t.ClassroomId, cascadeDelete: true)
        .Index(t => t.ClassroomId);
}

这是正常行为吗?看看它在SQL Server中的作用:

Awkward

1 个答案:

答案 0 :(得分:0)

它看起来像你有&#34;双映射&#34;你在两个EntityTypeConfiguration<T>课程中的关系。我认为你只需要在一个方向上定义关系。

Entity Framework Fluent API文档指出,对于一对一或一对一关系,请使用.HasOptional().WithRequired()中的ClassroomMap进行定义。您应该可以删除.HasRequired().WithOptional()课程中的ClassroomStreamingMap