[英]EF 6.1.1 - The relationship could not be changed because one or more of the foreign-key properties is non-nullable
[英]EF adding entity: The relationship could not be changed because one or more of the foreign-key properties is non-nullable
我正在嘗試向數據庫中添加一些新創建的實體,但是EF拋出一條InvalidOperationException
消息, The relationship could not be changed because one or more of the foreign-key properties is non-nullable
但是它不能告訴我哪個關系很重要。
以下是相關實體:
DatabaseContext OnModelCreating:
...
modelBuilder.Entity<Student>()
.HasRequired(s => s.Home)
.WithMany(s => s.StudentsInResidence)
.HasForeignKey(s => s.HomeId);
modelBuilder.Entity<SignoutRequest>()
.HasOptional(x => x.Destination)
.WithMany(x => x.RequestsToHere)
.HasForeignKey(x => x.DestinationId);
modelBuilder.Entity<SignoutRequest>()
.HasRequired(x => x.Subject)
.WithMany(x => x.SignoutRequests)
.HasForeignKey(x => x.SubjectId);
...
SignoutRequest:
public class SignoutRequest
{
public SignoutRequest()
{
}
public int Id { get; set; }
public string SubjectId { get; set; }
...
public int? DestinationId { get; set; }
#region Custom Fields
...
#endregion
#region Virtual Properties
...
public virtual Student Subject { get; set; }
public virtual DeviceGroup Destination { get; set; }
#endregion
}
學生:
public class Student : IWpEntity
{
public string Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public int Form { get; set; }
public int HomeId { get; set; }
public virtual DeviceGroup Home { get; set; }
public virtual ICollection<BlacklistEntry> BlacklistEntries { get; set; }
public virtual ICollection<SignoutRequest> SignoutRequests { get; set; }
}
DeviceGroup:
public class DeviceGroup : IWpEntity
{
public int Id { get; set; }
public string FriendlyName { get; set; }
public virtual ICollection<Device> Devices { get; set; }
public virtual ICollection<Student> StudentsInResidence { get; set; }
public virtual ICollection<SignoutRequest> RequestsToHere { get; set; }
}
IWpEntity只是方法的集合。
這是引發錯誤的代碼:
_database.SubmittedRequests.Add(srq);
await _database.SaveChangesAsync();
srq
是我要添加到數據庫中的SignoutRequest
。 它已經具有屬性SubjectId
和DestinationId
設置為數據庫中已經存在的對象的有效ID。
我完全不知道為什么,但是我擺脫了IWpEntity並開始工作。 我完全感到困惑,我也不知道為什么這會對數據庫產生任何影響。 Sql Management Studio中的數據庫設計看起來相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.