【发布时间】:2017-07-17 08:43:07
【问题描述】:
我正在使用实体框架。 ChatRoom 类有一个 TranscriptDownloadUserInfo 类的列表。现在,当我尝试清空时,正在使用 .Clear(),它显示“无法插入值 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语句已终止。
我不确定为什么会发生此错误。任何建议都将受到高度赞赏。
【问题讨论】:
标签: c# sql-server database entity-framework