2011-04-14 64 views
1

我在我的腳本收到此錯誤:ERROR:IDENTITY_INSERT設置爲OFF

Cannot insert explicit value for identity column in table 'GameMaster' when IDENTITY_INSERT is set to OFF.

這裏是正在執行的代碼:

 Dim db = New PlayerTestDataContextDataContext() 

    If txtNewGM.Text = "" Then 
     lbWarning.Text = "Please enter a name!" 
    Else 

     Dim GM As New GameMaster With { 
      .GameMasterName = txtNewGM.Text} 
     db.GameMasters.InsertOnSubmit(GM) 
     db.SubmitChanges() 

     Me.Close() 

    End If 

我在我的數據庫中的兩個表。 Player,它有一個PlayerID和PlayerName列。和GameMasters,它有一個GameMasterID,PlayerID和GameMasterName,PlayerID是播放器表格中的foriegn鍵。我有主鍵Identity SPecification在每張桌上設置了yes(玩家的PlayerID和GameMaster的GameMasterID)。什麼是造成這個錯誤。我周圍搜索,發現類似的問題,但沒有一個是完全相同的事情......

+2

-

protected void Page_Load(object sender, EventArgs e) { int beef; string aLing = String.Format("{0}", beef); } 

但不是?如果它有一個值,它會失敗,因爲它是該表上的IDENTITY的PK。 – 2011-04-14 17:01:44

+0

我忘記了如何在調試時查看這些值。 我使用幾乎完全相同的代碼來創建新的玩家,它的工作原理。唯一不同的是GameMaster類中有FK PlayerID。這可能是錯誤原因的一部分嗎? – Underonesky 2011-04-14 17:17:24

+0

劃痕。我沒有解決我的錯誤。 – Underonesky 2011-04-14 17:28:48

回答

0

很可能你有GameMaster類聲明的整數GameMasterID屬性。由於整數屬性默認設置爲零,所以當插入發生時,它試圖設置所有的屬性,包括GameMasterID屬性。所以它會嘗試將標識列設置爲零,失敗。

0

看起來您的數據訪問例程在執行插入操作時隱式傳遞非NULL值(可能爲隱式零值的auto-prop)。

我曾經遇到過這種錯誤的唯一時間是當我嘗試在數據庫表中創建新記錄並嘗試設置標識字段時。我想這可能是你得到它的唯一方法。

編輯:

幾乎可以肯定的自動道具在這裏打球。

奇怪的是,編譯器會保護你 - :在調試你可以看到`GM.GameMasterID`的價值

public int Beef { get; set; } 

protected void Page_Load(object sender, EventArgs e) 
{ 
    string aLing = String.Format("{0}", Beef); 
} 
相關問題