我正在使用實體框架。 ChatRoom類具有TranscriptDownloadUserInfo類的列表。現在,當我試圖清空使用.Clear(),它顯示我'不能插入值NULL';嘗試清空集合時出現'無法插入值NULL'錯誤顯示
ChatRoom.cs
public class ChatRoom
{
[Key]
public int Key { get; set; }
public virtual ICollection<TranscriptDownloadUserInfo> TranscriptDownAllowedUsers { get; set; }
public ChatRoom()
{
TranscriptDownAllowedUsers = new SafeCollection<TranscriptDownloadUserInfo>();
}
}
TranscriptDownloadUserInfo.cs
public class TranscriptDownloadUserInfo
{
[Key]
public int Key { get; set; }
public virtual ChatUser User { get; set; }
public int? UserKey { get; set; }
public bool Allowed { get; set; }
}
TranscriptDownloadUserInfo映射
public TranscriptDownloadUserInfoMap()
{
this.HasKey(t => t.Key);
this.ToTable("TranscriptDownAllowedUsers");
this.Property(t => t.Key).HasColumnName("Key");
this.Property(t => t.UserKey).HasColumnName("UserKey");
this.Property(t => t.Allowed).HasColumnName("Allowed");
this.HasRequired(t => t.User)
.WithMany()
.HasForeignKey(t => t.UserKey);
}
添加-遷移代碼
public override void Up()
{
CreateTable(
"dbo.TranscriptDownAllowedUsers",
c => new
{
Key = c.Int(nullable: false, identity: true),
UserKey = c.Int(nullable: false),
Allowed = c.Boolean(nullable: false, defaultValue: false),
ChatRoom_Key = c.Int(nullable: false),
})
.PrimaryKey(t => t.Key)
.ForeignKey("dbo.ChatUsers", t => t.UserKey, cascadeDelete: true)
.ForeignKey("dbo.ChatRooms", t => t.ChatRoom_Key)
.Index(t => t.UserKey)
.Index(t => t.ChatRoom_Key);
}
代碼生成錯誤
room.TranscriptDownAllowedUsers.Clear();
_repository.CommitChanges();
內異常
無法插入NULL值插入列 'ChatRoom_Key',表 'Dabb.dbo.TranscriptDownAllowedUsers';列不允許有空值。 UPDATE失敗。\ r \ n聲明已終止。
我不知道這是爲什麼錯誤發生。任何建議將不勝感激。
可能重複的[實體框架 - 清除子集合](http://stackoverflow.com/questions/2058697/entity-framework-clear-a-child-collection) –