我不明白为什么代码首先一个新项目不添加到集合中,直到调用的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
好,但为什么不在集合代表当前会话/事务?它现在代表了当前的数据库,我不关心这个。 –