- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我不明白为什么 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/
MVC3 中的助手是否在 Controller 和 View 中使用? 助手是放置常用 Controller 方法的正确位置吗? 我想创建一个通用方法来获取数据库中的所有子子 ID,并确保它位于正确的
有人可以阐明这两者之间的区别吗,因为它们存在于执行上下文中?我很难阅读 ECMA 262 v 5规范并清楚地看到差异。 谢谢你, 最佳答案 两者都是执行上下文的组件(相同类型),但它们有不同的用途(f
我是一名优秀的程序员,十分优秀!