次の方法で共有


ADO.NET と LINQ to SQL

LINQ to SQL は、ADO.NET テクノロジ ファミリの一部です。 これは、ADO.NET プロバイダー モデルによって提供されるサービスに基づいています。 そのため、LINQ to SQL コードを既存の ADO.NET アプリケーションと混在させ、現在の ADO.NET ソリューションを LINQ to SQL に移行できます。 次の図は、リレーションシップの概要を示しています。

LINQ to SQL と ADO.NET

接続

LINQ to SQL DataContextを作成するときに、既存の ADO.NET 接続を指定できます。 DataContextに対するすべての操作 (クエリを含む) では、この指定された接続が使用されます。 接続が既に開いている場合、LINQ to SQL では、完了するとそのまま残されます。

string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\northwind.mdf;
    Integrated Security=True; Connect Timeout=30; User Instance=True";
SqlConnection nwindConn = new SqlConnection(connString);
nwindConn.Open();

Northwnd interop_db = new Northwnd(nwindConn);

SqlTransaction nwindTxn = nwindConn.BeginTransaction();

try
{
    SqlCommand cmd = new SqlCommand(
        "UPDATE Products SET QuantityPerUnit = 'single item' WHERE ProductID = 3");
    cmd.Connection = nwindConn;
    cmd.Transaction = nwindTxn;
    cmd.ExecuteNonQuery();

    interop_db.Transaction = nwindTxn;

    Product prod1 = interop_db.Products
        .First(p => p.ProductID == 4);
    Product prod2 = interop_db.Products
        .First(p => p.ProductID == 5);
    prod1.UnitsInStock -= 3;
    prod2.UnitsInStock -= 5;

    interop_db.SubmitChanges();

    nwindTxn.Commit();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine("Error submitting changes... all changes rolled back.");
}

nwindConn.Close();
Dim conString = "Data Source=.\SQLEXPRESS;AttachDbFilename=c:\northwind.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim northwindCon = New SqlConnection(conString)
northwindCon.Open()

Dim db = New Northwnd("...")
Dim northwindTransaction = northwindCon.BeginTransaction()

Try
    Dim cmd = New SqlCommand( _
            "UPDATE Products SET QuantityPerUnit = 'single item' " & _
            "WHERE ProductID = 3")
    cmd.Connection = northwindCon
    cmd.Transaction = northwindTransaction
    cmd.ExecuteNonQuery()

    db.Transaction = northwindTransaction

    Dim prod1 = (From prod In db.Products _
                 Where prod.ProductID = 4).First
    Dim prod2 = (From prod In db.Products _
                 Where prod.ProductID = 5).First
    prod1.UnitsInStock -= 3
    prod2.UnitsInStock -= 5

    db.SubmitChanges()

    northwindTransaction.Commit()

Catch e As Exception

    Console.WriteLine(e.Message)
    Console.WriteLine("Error submitting changes... " & _
"all changes rolled back.")
End Try

northwindCon.Close()

次のコードのように、常に Connection プロパティを使用して接続にアクセスし、自分で接続を閉じることができます。

db.Connection.Close();
db.Connection.Close()

トランザクション

アプリケーションが既にトランザクションを開始しており、DataContextを関与させる場合は、DataContextに独自のデータベース トランザクションを指定できます。

.NET Framework でトランザクションを実行する場合は、 TransactionScope オブジェクトを使用することをお勧めします。 この方法を使用すると、データベースやその他のメモリ常駐リソース マネージャー間で動作する分散トランザクションを作成できます。 トランザクション スコープでは、開始する必要のあるリソースはほとんどありません。 トランザクションのスコープ内に複数の接続がある場合にのみ、分散トランザクションに昇格します。

using (TransactionScope ts = new TransactionScope())
{
    db.SubmitChanges();
    ts.Complete();
}
Using ts As New TransactionScope()
    db.SubmitChanges()
    ts.Complete()
End Using

この方法をすべてのデータベースに使用することはできません。 たとえば、SQLClient 接続は、SQL Server 2000 サーバーに対して動作する場合、システム トランザクションを昇格できません。 代わりに、使用されているトランザクション スコープが表示されるたびに、完全な分散トランザクションに自動的に参加します。

直接 SQL コマンド

変更を照会または送信する DataContext の能力が、実行する特殊なタスクに対して不十分な場合があります。 このような状況では、 ExecuteQuery メソッドを使用して SQL コマンドをデータベースに発行し、クエリ結果をオブジェクトに変換できます。

たとえば、 Customer クラスのデータが 2 つのテーブル (customer1 と customer2) に分散されているとします。 次のクエリは、 Customer オブジェクトのシーケンスを返します。

            IEnumerable<Customer> results = db.ExecuteQuery<Customer>(
    @"select c1.custid as CustomerID, c2.custName as ContactName
        from customer1 as c1, customer2 as c2
        where c1.custid = c2.custid"
);
    Dim results As IEnumerable(Of Customer) = _
db.ExecuteQuery(Of Customer)( _
"SELECT [c1].custID as CustomerID," & _
    "[c2].custName as ContactName" & _
    "FROM customer1 AS [c1], customer2 as [c2]" & _
    "WHERE [c1].custid = [c2].custid")

表形式の結果の列名がエンティティ クラスの列プロパティと一致する限り、LINQ to SQL は任意の SQL クエリからオブジェクトを作成します。

パラメーター

ExecuteQuery メソッドはパラメーターを受け入れます。 次のコードは、パラメーター化されたクエリを実行します。

            IEnumerable<Customer> results = db.ExecuteQuery<Customer>(
    "select contactname from customers where city = {0}",
    "London"
);
    Dim results As IEnumerable(Of Customer) = _
db.ExecuteQuery(Of Customer)( _
    "SELECT contactname FROM customers WHERE city = {0}, 'London'")
End Sub

パラメーターは、 Console.WriteLine()String.Format()で使用されるのと同じカーリー表記を使用して、クエリ テキストで表されます。 String.Format() は、指定したクエリ文字列を受け取り、中かっこで固定されたパラメーターを、 @p0@p1 ...、 @p(n) などの生成されたパラメーター名に置き換えます。

こちらも参照ください