2017-02-26 26 views
0

我正在使用實體框架。 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聲明已終止。

我不知道這是爲什麼錯誤發生。任何建議將不勝感激。

+1

可能重複的[實體框架 - 清除子集合](http://stackoverflow.com/questions/2058697/entity-framework-clear-a-child-collection) –

回答

1

我覺得這是一個矛盾nullable: false, identity: true,因爲你所定義的鍵列作爲一個標識,所以EF 假設null值可以插入到生成一個新的密鑰。

在這種情況下,你應該使它可以爲空。

也就是說,你的must使你的外鍵ChatRoom_Key爲空,因爲Clear必須刪除引用。

+0

好點。因爲我不需要那個關鍵列。讓我試着刪除它。然後讓我們看看會發生什麼 – Arnab

+0

我也更新了我的答案,發現了另一個問題:外鍵必須可以爲空 – 2017-02-26 21:26:47

0

您的字段不能爲空。

  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), 

您可以插入默認或somethings,但不能插入任何內容。

+0

通過做.clear(),我想刪除該房間的所有TranscriptDownAllowedUsers記錄,我不想將列值設置爲null。任何建議? – Arnab

+0

我假設聊天室中的每個用戶的所有聊天室密鑰都是相同的? – Flibertyjibbet

+0

會有多個chatRooms和多個聊天用戶 – Arnab

相關問題