簡體   English   中英

EF添加實體:由於一個或多個外鍵屬性不可為空,因此無法更改關系

[英]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 它已經具有屬性SubjectIdDestinationId設置為數據庫中已經存在的對象的有效ID。

我完全不知道為什么,但是我擺脫了IWpEntity並開始工作。 我完全感到困惑,我也不知道為什么這會對數據庫產生任何影響。 Sql Management Studio中的數據庫設計看起來相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM