Unhandled Exception after Upgrading to Entity Framework 4.3.1

前端 未结 5 732
无人共我
无人共我 2020-12-06 17:33

Error:

Unhandled Exception: System.Data.SqlClient.SqlException: The operation failed because an index or statistics with name \'IX_ID\' already exi

相关标签:
5条回答
  • 2020-12-06 18:08

    Below I describe 2 scenarios what is probably going wrong. Please read in depth by clicking the links I provided to know more about my explanation.


    First
    Lesson and RecurringLesson are abstract classes (so you want to have it as the base classes).
    You are creating a table of the Lesson and the RecurringLesson entities which will result in a Table per hierarchy structure. brief description
    Creating a class of the base table will result in one big table which contains the columns of all inherited tables. So all properties of PrivateLesson, MakeUpLesson and all others inherited entities will be stored in the Lessons table. EF will add also a Discriminator column. The value of this column defaults to the persistent class name (like "PrivateLesson" or "MakeUpLesson") only the column matching to that particular entity (matching the Discriminator value) will be used in that particular row.

    BUT
    You are also mapping the inherited classes like PrivateLesson and MakeUpLesson. This will force EF to use the Table per Type structure which results in one table per class. This can cause conflicts you are facing right now.


    Second
    Your example shows you have an one-to-one relationship (Cancellation -> MakeUpLesson) and a one-to-many relationship (Cancellation -> PrivateLesson) because PrivateLesson and MakeUpLessonare both (indirect) inherited from Lesson in combination with the first described scenario can cause problems because it will result in 2 foreign key relationships in the database per entity. (one using Table per hierarchy structure and one using the Table per Type structure).

    Also this post can help you defining a correct one-to-one definition.


    Please verify by performing the following steps:
    I assume you have your own test environment so you can create new test databases

    1. Delete the relationships to the Cancellation by commenting out all properties to this class:

    public class PrivateLesson : RecurringLesson
    {
        public string Student { get; set; }
        public string Teacher { get; set; }
        //public virtual ICollection<Cancellation> Cancellations { get; set; }
    }
    
    public class Cancellation
    {
        public Guid ID { get; set; }
        public DateTime Date { get; set; }
        //public virtual PrivateLesson Lesson { get; set; }
        //public virtual MakeUpLesson MakeUpLesson { get; set; }
    }
    
    public class MakeUpLesson : Lesson
    {
        public DateTime Date { get; set; }
        public string Teacher { get; set; }
        //public virtual Cancellation Cancellation { get; set; }
    }
    

    And remove the configuration to it:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Lesson>().ToTable("Lessons");
        modelBuilder.Entity<RecurringLesson>().ToTable("RecurringLessons");
        modelBuilder.Entity<PrivateLesson>().ToTable("PrivateLessons");
        modelBuilder.Entity<MakeUpLesson>().ToTable("PrivateMakeUpLessons");
    
        //modelBuilder.Entity<Cancellation>()
        //    .HasOptional(x => x.MakeUpLesson)
        //    .WithRequired(x => x.Cancellation);
    
        base.OnModelCreating(modelBuilder);
    }
    

    2. Create a new empty database
    3. Let EF generate the table structure for you in this empty database.
    4. Verify the first scenario. If that's true this need to be fixed first by using the Table per hierarchy structure OR the Table per Type structure. Probably you want to use the Table per hierarchy structure because (if I understand your question well) there is already an production environment.

    0 讨论(0)
  • 2020-12-06 18:09

    As of EF 4.3, indexes are added for freign key columns during database creation. There is a bug that can cause an index to be created more than once. This will be fixed in a future EF release.

    Until then, you can work around the issue by creating your database using Migrations instead of database initializers (or the Database.Create() method).

    After generating the initial migration, you will need to delete the redundant call to Index().

    CreateTable(
        "dbo.PrivateMakeUpLessons",
        c => new
            {
                ID = c.Guid(nullable: false),
                ...
            })
        .PrimaryKey(t => t.ID)
        .ForeignKey("dbo.Lessons", t => t.ID)
        .ForeignKey("dbo.Cancellations", t => t.ID)
        .Index(t => t.ID)
        .Index(t => t.ID); // <-- Remove this
    

    To continue creating your database at run-time, you can use the MigrateDatabaseToLatestVersion initializer.

    0 讨论(0)
  • 2020-12-06 18:10

    I got a very similar error to this one in my code a while back. Try putting the cancellation list inside the Lesson class. That's what solved my problem.

    0 讨论(0)
  • 2020-12-06 18:21

    When my project was updated from EF 6.0.2 to EF 6.1.1, I had such a problem, then back to 6.0.2, after the return of an older version, the error disappeared

    0 讨论(0)
  • 2020-12-06 18:25

    In my opinion this is clearly a bug.

    The problem starts with the observation that EF creates an index IX_ID at all. If you strip down the model to the following...

    public abstract class Lesson
    {
        public Guid ID { get; set; }
    }
    
    public class RecurringLesson : Lesson
    {
    }
    
    public class MyContext : DbContext
    {
        public DbSet<Lesson> Lessons { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<RecurringLesson>().ToTable("RecurringLessons");
        }
    }
    

    ... and let EF create the database schema you get two tables Lessons and RecurringLessons as expected for a TPT inheritance mapping. But I am wondering why it creates two indices for the table RecurringLessons:

    • Index PK_RecurringLessons (clustered, unique) with Index column ID
    • Index IX_ID (not clustered, not unique) with Index column ID again

    I don't know if there is any benefit for the database to have a second index on the same column. But for my understanding it doesn't make sense 1) to create an index on the same column that is already covered in the PK clustered index, and 2) to create a not unique index on a column which is the primary key and therefore necessarily unique.

    Moreover due to the one-to-one relationship EF tries to create an index on the table of the dependent of this association which is PrivateMakeUpLessons. (It's the dependent (and not the principal) because Cancellation is required in entity MakeUpLesson.)

    ID is the foreign key in this association (and primary key at the same time because one-to-one relationships are always shared primary key associations in Entity Framework). EF apparently always creates a index on the foreign key of a relationship. But for one-to-many relationships this is not a problem because the FK column is different from the PK column. Not so for one-to-one relatonships: The FK and PK are the same (that is ID), hence EF tries to create an index IX_ID for this one-to-one relationship which already exists due to the TPT inheritance mapping (which leads to a one-to-one relationship as well from database perspective).

    The same consideration as above applies here: The table PrivateMakeUpLessons has a clustered PK index on column ID. Why is a second index IX_ID on the same column required at all?

    In addition EF doesn't seem to check that it already wants to create an Index with name IX_ID for the TPT inheritance, leading finally to the exception in the database when the DDL is sent to create the database schema.

    EF 4.2 (and before) didn't create any indices (except PK indices) at all, this was introduced in EF 4.3, especially indices for FK columns.

    I didn't find a workaround. In the worst case you have to create the database schema manually and avoid that EF tries to create it (= disable database initialization). In the best case there is a way to disable automatic FK index creation, but I don't know if it's possible.

    You can submit a bug report here: http://connect.microsoft.com/VisualStudio

    Or maybe someone from EF development team will see your question here and provide a solution.

    0 讨论(0)
提交回复
热议问题