在EF Core中,在“断开连接的方案中插入数据”与“在连接的方案中插入数据”之间有什么区别?
断开连接时插入数据的示例:
//Disconnected entity
var std = new Student(){ Name = "Bill" };
using (var context = new SchoolContext())
{
//1. Attach an entity to context with Added EntityState
context.Add<Student>(std);
//or the followings are also valid
// context.Students.Add(std);
// context.Entry<Student>(std).State = EntityState.Added;
// context.Attach<Student>(std);
//2. Calling SaveChanges to insert a new record into Students table
context.SaveChanges();
}
并在“已连接”中插入数据示例:
using (var context = new SchoolContext())
{
var std = new Student()
{
FirstName = "Bill",
LastName = "Gates"
};
context.Students.Add(std);
// or
// context.Add<Student>(std);
context.SaveChanges();
}
这个问题对我来说是这个网站的源头=> click here
答案 0 :(得分:0)
在连接的场景中,相同的DbContext实例用于检索和保存实体。
在断开连接的情况下,DbContext不知道断开连接的实体,因为在当前DbContext实例的范围之外添加或修改了实体。因此,您需要将断开连接的实体附加到具有适当EntityState的上下文,以便对数据库执行CUD(创建,更新,删除)操作。
我认为连接场景是最好的解决方案,因为我们不需要创建实体的新对象。