我有一個名爲Employee
的實體。它有一個名爲CreatedById
的可以爲空的屬性,它可以用作自己的參考。它必須是空的,因爲第一個記錄(可能是管理員)不會有創建者。當數據庫正在初始化時,當插入第一個Employee
對象時,我不斷收到錯誤,我認爲這是因爲我更新了與Fluent API的關係。代碼如下:實體框架6.1 - SaveChanges失敗,帶有可選主體關係
的Employee
類:
public class Employee : NullableInt32Entity, IUser<int> {
/// Omitted code that doesn't matter
}
的NullableInt32Entity
類Employee
繼承:
public class NullableInt32Entity :
Entity,
ICreatableEntity<int?>,
IIndexableEntity<int> {
#region ICreatableEntity Members
public int? CreatedById { get; set; }
#endregion
#region IIndexableEntity Members
public int Id { get; set; }
#endregion
}
在EmployeeConfiguration
類,我認爲是造成問題的配置:
this.HasOptional(
t =>
t.CreatedBy).WithOptionalPrincipal();
DatabaseInitializer
類:
internal sealed class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext> {
protected override void Seed(
DatabaseContext context) {
Employee creator = new Employee {
FirstName = "System",
IsActive = true,
LastName = "Administrator",
PasswordHash = "AIw9zIWiDnIesTaYhSjJhHJo5VYWCUV1rH0Oa0TaTriQXiDmXDBSq5y8Q0Zv3KUw/Q=="
};
context.Employees.Add(creator);
context.SaveChanges();
/// Additional seeds that depend on the one above as their creator.
}
}
而最後,但並非最不重要的例外,我得到:實體在「DatabaseContext.Employees」參加「Equipment_CreatedBy」的關係。找到0條相關'Equipment_CreatedBy_Source'。預計1'Equipment_CreatedBy_Source'。
所以,我的問題是,我該如何解決這個問題?我今天第一次開始使用WithOptionalPrincipal()
和WithRequiredPrincipal()
,因爲我意識到我不在乎從Employee
到任何其他對象的導航屬性。我曾在Employee
中爲每個其他對象擁有一個XCreated
集合導航屬性,我意識到他們沒有意義公開,因爲我永遠不會使用它們。因此,我將它們剝離出來,不得不使用上述方法。
我很欣賞任何建議,並提前致謝!
您確定每個創作者實體(您在CreatedBy屬性中使用)只能在一個Employee實體中使用?看起來你應該使用一對多的關係。 –
@KirillBestemyanov,是的,你是對的,那就是我想要的。我想我不太明白'WithXPrincipal()'。我嘗試用'this.HasOptional(t => t.CreatedBy).WithMany()。HasForeignKey(k => k.CreatedById)'替換它,但我仍然得到相同的異常。建議? – Gup3rSuR4c
異常消息中有設備實體。你能展示它的代碼(類和配置)嗎? –