I am using Entity Framework. Class ChatRoom has a List of TranscriptDownloadUserInfo class. Now when I am trying empty is using .Clear(), its showing me 'Cannot insert the value 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 Mapping
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);
}
Add-Migration code
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);
}
Code that generating the error
room.TranscriptDownAllowedUsers.Clear();
_repository.CommitChanges();
Inner-Exception
Cannot insert the value NULL into column 'ChatRoom_Key', table 'Dabb.dbo.TranscriptDownAllowedUsers'; column does not allow nulls. UPDATE fails.\r\nThe statement has been terminated.
I am not sure why is this error is occurring. Any suggestion will be highly appreciated.