我不明白爲什麼代碼首先一個新項目不添加到集合中,直到調用的SaveChanges之後。我從NuGet(4.1.10331.0)安裝了EF4.1。我創建了下面的例子:EF4代碼首先添加項目我不太清楚
public class TinyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TinyContext : DbContext
{
public virtual DbSet<TinyItem> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var ctx1 = new TinyContext())
{
ListItems(ctx1, "Start");
ctx1.Items.Add(new TinyItem { Name = "Test1" });
ListItems(ctx1, "After add");
ctx1.SaveChanges();
ListItems(ctx1, "After commit");
}
Console.ReadKey();
}
public static void ListItems(TinyContext ctx, string label="")
{
Console.WriteLine("=========================================");
Console.WriteLine(label);
Console.WriteLine(string.Format("Items.Local: {0}", ctx.Items.Local.Count));
foreach (var item in ctx.Items.Local)
{
Console.WriteLine(string.Format("{0} = {1}", item.Id, item.Name));
}
Console.WriteLine(string.Format("Items: {0}", ctx.Items.Count()));
foreach (var item in ctx.Items)
{
Console.WriteLine(string.Format("{0} = {1}", item.Id, item.Name));
}
Console.WriteLine("=========================================");
}
首先,我增加了一個記錄到數據庫中。然後我跑了這一點,這是結果:
=========================================
Start
Items.Local: 0
Items: 1
4 = Test1
=========================================
=========================================
After add
Items.Local: 2
4 = Test1
0 = Test1
Items: 1
4 = Test1
=========================================
=========================================
After commit
Items.Local: 2
4 = Test1
5 = Test1
Items: 2
4 = Test1
5 = Test1
=========================================
我的問題是: - 爲什麼到ctx.Items.Local第一個電話給我零級的項目? - 爲什麼在我調用SaveChanges之前,ctx.Items列表中不包含剛添加的項目?
關於最後一個問題:這是關於收集的SaveChanges,有沒有添加的項目(「添加後」一節)了。 –
@約翰編輯答案 – Eranga
好,但爲什麼不在集合代表當前會話/事務?它現在代表了當前的數據庫,我不關心這個。 –