gpt4 book ai didi

c# - EF4 代码首先添加项目我不是很清楚

转载 作者:太空狗 更新时间:2023-10-29 23:26:05 26 4
gpt4 key购买 nike

我不明白为什么 code first 在调用 savechanges 之后才向集合中添加新项目。我从 NuGet (4.1.10331.0) 安装了 EF4.1。我创建了以下示例:

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 会给我零个项目?- 为什么 ctx.Items 列表不包含我调用 SaveChanges 之前刚刚添加的项目?

最佳答案

Why does the first call to ctx.Items.Local give my zero items?

因为 EF 尚未从数据库中加载任何项目(或者您尚未添加任何项目)。因此它还没有跟踪任何项目。这显示为 0

这是 Local 的 msdn 描述

Returns ObservableCollection that represents entities of the set that are currently being tracked by the context and have not been marked as Deleted. Accessing the Local property never causes a query to be sent to the database. This property is usually used after a query has already been executed.


Why does the list of ctx.Items not contain the just added item before I called SaveChanges?

当您引用 ctx.Items 时,它将从数据库中获取。由于数据库中只有 1 个项目(您尚未调用 SaveChanges() 方法),因此它会显示数据库中的项目。

关于c# - EF4 代码首先添加项目我不是很清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com