我有一個EntityFramework
測試應用程序。 Select
查詢工作正常。我想Insert
到我的數據庫的新行。我在下面的代碼這樣做:爲什麼EntityFramework更新上下文,但不更新數據庫?
static void Main(string[] args)
{
using (Database1Entities context = new Database1Entities())
{
Console.WriteLine("Current data in Table:");
Console.WriteLine();
var selectQuery = from person in context.Person
select person;
foreach (var person in selectQuery)
{
Console.WriteLine("{0}. {1} - {2}", person.id, person.Name, person.Age);
}
Console.WriteLine();
Console.WriteLine("---------------------------------------");
Console.WriteLine("Try to add the new object to a table:");
Console.WriteLine();
Person newItem = new Person();
newItem.Name = "Tanya";
newItem.Age = 20;
context.Person.Add(newItem);
context.SaveChanges();
var selectQuery2 = from person in context.Person
select person;
foreach (var person in selectQuery2)
{
Console.WriteLine("{0}. {1} - {2}", person.id, person.Name, person.Age);
}
}
Console.ReadKey();
}
我有這樣的輸出:表
當前數據:
- 弗拉德 - 20
- 伊戈爾 - 27
嘗試新的對象添加到表:
- 弗拉德 - 20
- 伊戈爾 - 27
- 蔡健雅 - 20
而這個數據庫中的數據:
id name age
1 Vlad 20
2 Igor 27
輸出顯示發生了更改,但數據庫不更新d,沒有變化!
你的輸出似乎不同意你的看法。您是否嘗試過關閉上下文並在執行選擇查詢之前打開一個新的上下文?我想你會發現譚雅還在那裏。 –
試過了,但沒有效果。譚雅保存在文章中,但沒有保存在數據庫中! – BJladu4
以前有沒有爲你工作?您正在檢查的數據庫是否與上下文連接的數據庫相同?你在找正確的桌子嗎?當你發現真正的問題時,你會感到非常愚蠢。 –