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();
}
這個屬性會傳回傳遞給建構函式 (Constructor) 或在建構期間建立的連接物件。 線上擁有權是由使用的建構函式所決定。
產品 | 版本 |
---|---|
.NET Framework | 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |