Share via


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은 사용자의 작업이 끝났을 때 연결을 그대로 둡니다.

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()
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();

다음 코드와 같이 Connection 속성을 사용하여 항상 연결에 액세스하고 연결을 닫을 수 있습니다.

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

트랜잭션

응용 프로그램에서 이미 고유한 데이터베이스 트랜잭션을 시작했으며 DataContext를 관련시키려는 경우 해당 트랜잭션을 DataContext에 제공할 수 있습니다.

.NET Framework와 함께 트랜잭션을 수행하는 기본 방법은 TransactionScope 개체를 사용하는 것입니다. 이 방법을 사용하면 데이터베이스 및 다른 메모리 상주 리소스 관리자 사이에서 작동하는 분산 트랜잭션을 만들 수 있습니다. 트랜잭션 범위는 시작하는 데 리소스가 거의 필요하지 않습니다. 트랜잭션 범위는 해당 범위 내에 여러 연결이 있는 경우에만 분산 트랜잭션으로 승격됩니다.

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

이 방법을 모든 데이터베이스에 사용할 수 있는 것은 아닙니다. 예를 들어 SqlClient 연결은 SQL Server 2000 서버에 대해 작동할 경우 시스템 트랜잭션을 승격할 수 없습니다. 대신에 사용 중인 트랜잭션 범위가 있을 때마다 완전한 분산 트랜잭션에 자동으로 참여합니다.

SQL 명령 직접 실행

DataContext를 사용하여 변경 내용을 쿼리하거나 전송하는 기능으로는 원하는 특수한 작업을 수행할 수 없는 경우가 종종 있습니다. 이러한 상황에서는 ExecuteQuery 메서드를 사용하여 SQL 명령을 데이터베이스에 대해 실행하고 쿼리 결과를 개체로 변환할 수 있습니다.

예를 들어 Customer 클래스의 데이터가 두 개의 테이블(customer1 및 customer2)에 퍼져 있다고 가정해 봅니다. 다음 쿼리는 Customer 개체의 시퀀스를 반환합니다.

    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")
            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"
);

표 형식 결과의 열 이름이 엔터티 클래스의 열 속성과 일치할 경우 LINQ to SQL은 모든 SQL 쿼리에서 개체를 만듭니다.

매개 변수

ExecuteQuery 메서드에서는 매개 변수가 허용됩니다. 다음 코드는 매개 변수화된 쿼리를 실행합니다.

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

매개 변수는 Console.WriteLine() 및 String.Format()에서 사용되는 동일한 중괄호 표기법을 사용하여 쿼리 텍스트에서 표현됩니다.String.Format()은 제공된 쿼리 문자열을 가지며 중괄호로 묶인 매개 변수를 @p0, @p1 …, @p(n) 등과 같은 생성된 매개 변수 이름으로 대체합니다.

참고 항목

작업

방법: ADO.NET 명령과 DataContext 간의 연결 다시 사용(LINQ to SQL)

기타 리소스

배경 정보(LINQ to SQL)