ObjectContext.Connection 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取对象上下文使用的连接。
public:
property System::Data::Common::DbConnection ^ Connection { System::Data::Common::DbConnection ^ get(); };
public System.Data.Common.DbConnection Connection { get; }
member this.Connection : System.Data.Common.DbConnection
Public ReadOnly Property Connection As DbConnection
属性值
一个作为连接的 DbConnection 对象
例外
当释放了 ObjectContext 实例时。
示例
本示例创建一个 EntityConnection 对象,该对象将传递到长时间运行的 ObjectContext 的构造函数中。 此连接以手动方式建立。 EntityConnection 对象和 ObjectContext 对象都是手动释放的。
// Define the order ID for the order we want.
int orderId = 43680;
// Create an EntityConnection.
EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities");
// Create a long-running context with the connection.
AdventureWorksEntities context =
new AdventureWorksEntities(conn);
try
{
// Explicitly open the connection.
if (conn.State != ConnectionState.Open)
{
conn.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;
// You do not have to call the Load method to load the details for the order,
// because lazy loading is set to true
// by the constructor of the AdventureWorksEntities object.
// With lazy loading set to true the related objects are loaded when
// you access the navigation property. In this case SalesOrderDetails.
// Delete the first item in the order.
context.DeleteObject(order.SalesOrderDetails.First());
// Save changes.
if (0 < context.SaveChanges())
{
Console.WriteLine("Changes saved.");
}
// Create a new SalesOrderDetail object.
// You can use the static CreateObjectName method (the Entity Framework
// adds this method to the generated entity types) instead of the new operator:
// SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0,
// Guid.NewGuid(), DateTime.Today));
SalesOrderDetail detail = new SalesOrderDetail
{
SalesOrderID = 1,
SalesOrderDetailID = 0,
OrderQty = 2,
ProductID = 750,
SpecialOfferID = 1,
UnitPrice = (decimal)2171.2942,
UnitPriceDiscount = 0,
LineTotal = 0,
rowguid = Guid.NewGuid(),
ModifiedDate = DateTime.Now
};
order.SalesOrderDetails.Add(detail);
// Save changes again.
if (0 < context.SaveChanges())
{
Console.WriteLine("Changes saved.");
}
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
// Explicitly dispose of the context and the connection.
context.Dispose();
conn.Dispose();
}
注解
此属性返回传递给构造函数或在构造过程中创建的连接对象。 连接的所有权由所使用的构造函数决定。