[英]How to save changes in a DB for C#
我試圖在此處保存更改,並且在db.SaveChanges();上遇到異常錯誤。 我試圖將一些內容輸入數據庫,並說需要進行驗證。
這是錯誤:
一個或多個實體的驗證失敗。 有關更多詳細信息,請參見'EntityValidationErrors'屬性。
說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。
異常詳細信息:System.Data.Entity.Validation.DbEntityValidationException:對一個或多個實體的驗證失敗。 有關更多詳細信息,請參見'EntityValidationErrors'屬性。
using (GameConnection db = new GameConnection())
{
Game newGame = new Game();
int GameID = 0;
if (Request.QueryString.Count > 0)
{
GameID = Convert.ToInt32(Request.QueryString["gameID"]);
newGame = (from game in db.Games
where game.gameID == GameID
select game).FirstOrDefault();
}
newGame.teamA = teamATextBox.Text;
newGame.teamB = teamBTextBox.Text;
if (GameID == 0)
{
db.Games.Add(newGame);
}
db.SaveChanges();
Response.Redirect("~/Default.aspx");
}
}
該錯誤表明在將請求提交到數據庫之前,至少有一個驗證規則失敗。
您需要做的是檢查Game
(或數據庫表)的類定義,並檢查NotNull
或其他限制,並通過在db.SaveChanges();
之前調試Game
對象來檢查輸入是否符合所有這些限制db.SaveChanges();
更好的是,添加捕獲以將失敗的Properties
打印到Console
:
using (GameConnection db = new GameConnection())
{
Game newGame = new Game();
int GameID = 0;
if (Request.QueryString.Count > 0)
{
GameID = Convert.ToInt32(Request.QueryString["gameID"]);
newGame = (from game in db.Games
where game.gameID == GameID
select game).FirstOrDefault();
}
newGame.teamA = teamATextBox.Text;
newGame.teamB = teamBTextBox.Text;
if (GameID == 0)
{
db.Games.Add(newGame);
}
try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine(ve.PropertyName + " " + ve.ErrorMessage);
}
}
Response.Redirect("~/Default.aspx");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.