这是进行交易的标准方式。
您可以组合多个查询。
using (var context = new SchoolContext())
{
var std = new Student()
{
FirstName = "Bill",
LastName = "Gates"
};
context.Students.Add(std);
// or
// context.Add<Student>(std);
context.SaveChanges();
std = context.Students.First<Student>();
std.FirstName = "Steve";
context.SaveChanges();
}
ef 核心可以使用相同的连接或不同的连接或基于连接池。
Ef核心有连接和断开的事务模式。我想这可以适合你。
在断开连接的情况下保存数据与在连接的情况下略有不同。在断开连接的情况下,DbContext 不知道断开连接的实体,因为在当前 DbContext 实例的范围之外添加或修改了实体。因此,您需要将断开连接的实体附加到具有适当 EntityState 的上下文中,以便对数据库执行 CUD(创建、更新、删除)操作。
下图说明了断开场景下的CUD操作:
根据上图,断开连接的实体(未被 DbContext 跟踪的实体)需要使用适当的 EntityState 附加到 DbContext。例如,新实体的已添加状态,已编辑实体的已修改状态和已删除实体的已删除状态,这将在调用 SaveChanges() 方法时导致数据库中的 INSERT、UPDATE 或 DELETE 命令。
在断开连接的情况下,必须执行以下步骤才能使用 Entity Framework Core 在数据库表中插入、更新或删除记录:
使用适当的 EntityState 将实体附加到 DbContext,例如添加、修改或删除
调用 SaveChanges() 方法
以下示例演示了使用上述步骤将新记录插入数据库:
//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();
}
在上面的示例中,std 是 Student 实体的断开连接的实例。 context.Add() 方法将 Student 实体附加到具有已添加状态的上下文。 SaveChanges() 方法构建并执行以下 INSERT 语句:
exec sp_executesql N'SET NOCOUNT ON;
https://www.entityframeworktutorial.net/efcore/saving-data-in-disconnected-scenario-in-ef-core.aspx
这些是重要的方法。
public DbContext(DbConnection existingConnection, bool contextOwnsConnection)
public DbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
EF6 和未来版本中的行为
对于 EF6 和未来版本,我们采取的方法是,如果调用代码选择通过调用 context.Database.Connection.Open() 打开连接,那么它有充分的理由这样做,并且框架将假定它想要控制打开和关闭连接,并且不会再自动关闭连接。
注意
这可能会导致连接长时间打开,因此请小心使用。
我们还更新了代码,以便 ObjectContext.Connection.State 现在可以正确跟踪底层连接的状态。
using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Infrastructure;
namespace ConnectionManagementExamples
{
internal class DatabaseOpenConnectionBehaviorEF6
{
public static void DatabaseOpenConnectionBehavior()
{
using (var context = new BloggingContext())
{
// At this point the underlying store connection is closed
context.Database.Connection.Open();
// Now the underlying store connection is open and the
// ObjectContext.Connection.State correctly reports open too
var blog = new Blog { /* Blog’s properties */ };
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection remains open for the next operation
blog = new Blog { /* Blog’s properties */ };
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection is still open
} // The context is disposed – so now the underlying store connection is closed
}
}
}
https://docs.microsoft.com/en-us/ef/ef6/fundamentals/connection-management?redirectedfrom=MSDN