我正在尝试将一些新创建的实体添加到我的数据库中,但是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。
答案 0 :(得分:0)
我完全不知道为什么,但是我摆脱了IWpEntity并开始工作了。我完全糊涂了,我不知道为什么会对数据库有任何影响。 Sql Management Studio中的数据库设计看起来完全相同。