다음을 통해 공유


방법: 데이터베이스에 연결(LINQ to SQL)

DataContext는 데이터베이스에 연결하여 개체를 검색하고 변경 내용을 데이터베이스로 다시 전송하는 주 통로입니다. ADO.NET SqlConnection을 사용하는 것처럼 DataContext를 사용합니다. 실제로 DataContext는 사용자가 지정한 연결 또는 연결 문자열을 통해 초기화됩니다. 자세한 내용은 DataContext 메서드(O/R 디자이너)를 참조하십시오.

DataContext의 용도는 개체에 대한 요청을 데이터베이스에 적용할 수 있는 SQL 쿼리로 변환한 다음 결과 외의 개체를 어셈블하는 것입니다. DataContext에서는 Where 및 Select 등의 표준 쿼리 연산자와 같은 동일한 연산자 패턴을 구현하여 LINQ(통합 언어 쿼리)를 사용할 수 있습니다.

보안 정보보안 정보

보안 연결을 유지 관리하는 것이 가장 중요합니다.자세한 내용은 LINQ to SQL의 보안을 참조하십시오.

예제

다음 예제에서는 DataContext를 사용하여 Northwind 샘플 데이터베이스에 연결한 다음 도시가 London인 고객의 행을 검색합니다.

' DataContext takes a connection string.
Dim db As New DataContext("…\Northwnd.mdf")

' Get a typed table to run queries.
Dim Customers As Table(Of Customer) = db.GetTable(Of Customer)()

' Query for customer from London.
Dim Query = _
    From cust In Customers _
    Where cust.City = "London" _
    Select cust

For Each cust In Query
    Console.WriteLine("id=" & cust.CustomerID & _
        ", City=" & cust.City)
Next
// DataContext takes a connection string. 
DataContext db = new DataContext(@"c:\Northwnd.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London.
var query =
    from cust in Customers
    where cust.City == "London"
    select cust;

foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);

각 데이터베이스 테이블은 해당 테이블을 식별할 수 있는 엔터티 클래스를 사용하여 GetTable 메서드를 통해 사용할 수 있는 Table 컬렉션으로 나타납니다.

가장 좋은 방법은 기본 DataContext 클래스와 GetTable 메서드를 사용하는 대신 강력한 형식의 DataContext를 선언하는 것입니다. 강력한 형식의 DataContext에서는 다음 예제와 같이 Table 컬렉션을 컨텍스트의 멤버로 선언합니다.

Partial Public Class Northwind
    Inherits DataContext
    Public Customers As Table(Of Customer)
    Public Orders As Table(Of Order)
    Public Sub New(ByVal connection As String)
        MyBase.New(connection)
    End Sub
End Class
public partial class Northwind : DataContext
{
    public Table<Customer> Customers;
    public Table<Order> Orders;
    public Northwind(string connection) : base(connection) { }
}

그런 다음 London에 있는 고객에 대한 쿼리를 다음과 같이 더 간단하게 표현할 수 있습니다.

Dim db As New Northwind("...\Northwnd.mdf")

Dim query = _
    From cust In db.Customers _
    Where cust.City = "London" _
    Select cust

For Each cust In query
    Console.WriteLine("id=" & cust.CustomerID & _
        ", City=" & cust.City)
Next
Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
var query =
    from cust in db.Customers
    where cust.City == "London"
    select cust;
foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID,
        cust.City);

참고 항목

기타 리소스

데이터베이스와 통신(LINQ to SQL)