如何:手动从对象上下文打开连接(实体框架)

本主题提供有关如何手动从对象上下文打开连接的示例。

本主题中的示例基于 AdventureWorks 销售模型。 若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架。 为此,请完成如何:使用实体数据模型向导(实体框架) 中的过程。

示例

本示例手动打开连接,然后执行查询并保存更改。 当上下文离开作用域并被释放时,将关闭此连接。

' Define the order ID for the order we want. 
Dim orderId As Integer = 43680

Using context As New AdventureWorksEntities()
    ' Explicitly open the connection. 
    context.Connection.Open()

    ' Execute a query to return an order. 
    Dim order As SalesOrderHeader = context.SalesOrderHeaders.Where("it.SalesOrderID = @orderId", _
                                        New ObjectParameter("orderId", orderId)).Execute(MergeOption.AppendOnly).First()


    ' Change the status of the order. 
    order.Status = 1

    ' Save changes. 
    If 0 < context.SaveChanges() Then
        Console.WriteLine("Changes saved.")
    End If
    ' The connection is closed when the object context 
    ' is disposed because it is no longer in scope. 
End Using
// Define the order ID for the order we want.
int orderId = 43680;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Explicitly open the connection.    
    context.Connection.Open();

    // Execute a query to return an order.
    SalesOrderHeader order =
        context.SalesOrderHeaders.Where(
        "it.SalesOrderID = @orderId", new ObjectParameter("orderId", orderId))
        .Execute(MergeOption.AppendOnly).First();


    // Change the status of the order.
    order.Status = 1;

    // Save changes.
    if (0 < context.SaveChanges())
    {
        Console.WriteLine("Changes saved.");
    }
    // The connection is closed when the object context
    // is disposed because it is no longer in scope.
}

另请参见

任务

如何:在长时间运行的对象上下文中管理连接(实体框架)
如何:将 EntityConnection 用于对象上下文(实体框架)