2015-04-02 58 views
1

我試圖將一些新創建的實體添加到我的數據庫中,但是EF正在向消息中拋出一個InvalidOperationExceptionThe relationship could not be changed because one or more of the foreign-key properties is non-nullable但它不告訴我哪個關係是問題。EF添加實體:關係無法更改,因爲一個或多個外鍵屬性不可爲空

下面是相關實體:

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。它已將屬性SubjectIdDestinationId設置爲數據庫中已有對象的有效ID。

回答

0

我完全不知道爲什麼,但我擺脫了IWpEntity並開始工作。我完全困惑,我不知道爲什麼這對數據庫有任何影響。 Sql Management Studio中的數據庫設計看起來完全相同。

相關問題