錯誤:未處理的異常4.3.1
未處理的異常信息:System.Data.SqlClient.SqlException:操作失敗,因爲索引或統計名爲「IX_ID」表上已經存在「 PrivateMakeUpLessons'。
模型(簡體,建立在調試一個單獨的測試項目):
public abstract class Lesson
{
public Guid ID { get; set; }
public string Room { get; set; }
public TimeSpan Time { get; set; }
public int Duration { get; set; }
}
public abstract class RecurringLesson : Lesson
{
public int DayOfWeek { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Frequency { get; set; }
}
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; }
}
配置:
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);
}
注意:
這工作得很好EF 4.2。我的模型有問題嗎?實際的模型要複雜得多,這就是爲什麼我將所有類都抽象出來的原因。另外,我正在處理現有的數據庫,所以我需要使用Table-Per-Type繼承。
如果我將Cancellation
到PrivateMakeUpLesson
的關係從1改變到0..1到0..1到0..1,它就起作用。這是不可取的,因爲如果沒有Cancellation
,就不能有PrivateMakeUpLesson
。
此外,如果我讓PrivateMakeUpLesson
不從Lesson
繼承,那麼它也可以工作,但它是一個教訓,需要保留現有的業務邏輯。
我很感激任何指導。謝謝!
編輯:
開始賞金。我無法找到有關EF 4.2和EF 4.3之間在代碼優先的索引生成方面發生了什麼變化的任何文檔。很明顯,EF 4.3創建了更多的索引,並且命名方案已經改變,但我想知道EF中是否存在錯誤,或者我的模型或流利API配置是否存在根本性錯誤。
你的錯誤提到你正在使用現有的數據庫,但是這個錯誤看起來更像是EF試圖創建和索引 - 這隻有在EF修改數據庫模式時纔會發生。你使用EF遷移? –
@LadislavMrnka不,我仍然手動編寫遷移腳本。我剛纔提到我已經在生產中有一個數據庫,所以我不想更改繼承映射方法。 –
我同意這聽起來像它嘗試重新創建數據庫,因爲您正在使用自定義遷移腳本,您是否禁用了數據庫的重新創建約定? –