언어
이 항목에서는 SQL Server Compact 데이터베이스를 데이터 원본으로 사용하는 Entity Framework 응용 프로그램을 만드는 방법에 대한 단계별 지침을 제공합니다.
새 Entity Framework 응용 프로그램을 만들려면
Visual Studio의 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 선택합니다.
새 프로젝트 대화 상자의 프로젝트 형식 목록에서 사용할 프로그래밍 언어를 확장한 다음 Visual C# 또는 Visual Basic을 선택합니다.
템플릿 목록에서 콘솔 응용 프로그램을 선택합니다.
프로젝트 이름(예: SQLCompactEDMProject)과 위치를 지정한 다음 확인을 클릭합니다.
Northwind.sdf에 대한 엔터티 데이터 모델을 만들려면 %ProgramFiles%\Microsoft SQL Server Compact Edition\v3.5\Samples 폴더에 있는 Northwind.sdf를 프로젝트가 있는 폴더로 복사합니다.
프로젝트 메뉴에서 새 항목 추가를 클릭합니다.
템플릿 창에서 ADO.NET 엔터티 데이터 모델을 선택합니다.
모델 이름으로 Northwind.edmx를 입력한 다음 추가를 클릭합니다.
엔터티 데이터 모델 마법사의 첫 번째 페이지가 표시됩니다.
모델 콘텐츠 선택 대화 상자에서 데이터베이스에서 생성을 선택합니다. 그런 다음 다음을 클릭합니다.
새 연결 단추를 클릭합니다.
연결 속성 대화 상자의 데이터 원본에서 변경 단추를 클릭합니다. Microsoft SQL Server Compact 3.5를 선택하고 Northwind.sdf로 이동한 다음 확인을 클릭합니다.
데이터 연결 선택 대화 상자가 데이터베이스 연결 설정으로 업데이트됩니다.
App.Config의 엔터티 연결 설정을 다음으로 저장: 확인란을 선택했으며 값이 NorthwindEntities로 설정되었는지 확인합니다. 그런 다음 다음을 클릭합니다.
데이터베이스 개체 선택 대화 상자에서 모든 개체를 지우고 테이블을 확장하고 Customers를 테이블 개체로 선택합니다.
모델 네임스페이스로 NorthwindModel을 입력합니다.
마침을 클릭하여 마법사를 완료합니다.
이 마법사는 다음을 수행합니다.
- System.Data.Entity.dll, System.Runtime.Serialization.dll 및 System.Security.dll 어셈블리에 대한 참조를 추가합니다.
- EDM를 정의하는 Northwind.edmx 파일을 생성합니다.
- EDM을 기반으로 생성된 클래스를 포함하는 원본 코드 파일을 만듭니다. 솔루션 탐색기에서 .edmx 파일을 확장하여 원본 코드 파일을 볼 수 있습니다.
- App.Config 파일을 만듭니다.
프로젝트의 응용 프로그램 구성 파일(app.config)을 두 번 클릭하고 연결 문자열에서 provider=System.Data.SqlServerCe.3.5를 확인합니다.
응용 프로그램에 대한 코드 페이지에서 문을 사용하여 다음을 추가합니다.
C#:
using NorthwindModel;Visual Basic:
Imports SQLCompactEDM.NorthwindModel모델 이름은 Northwind.edmx 파일에 지정된 네임스페이스의 값에 해당합니다.
다음 코드 예를 코드 파일에 복사합니다. 그리고 나서 컴파일하고 실행합니다.
중요
System.Data.Entity.dll 어셈블리는 SP1 릴리스의 .NET Framework 버전 3.5에 포함되어 있습니다. System.Data.Entity 네임스페이스에 대한 관리되는 참조 항목은 Entity Framework 설명서에서 제공됩니다.
예
다음 코드 예에서는 SQL Server Compact Northwind.sdf 데이터베이스에 대해 3개의 단순 Entity Framework 쿼리를 제공합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data;
using NorthwindModel;
namespace SQLCompactEDMProject
{
class SSC_EntityFrameworkExample
{
static void Main(string[] args)
{
Console.WriteLine(
"SQL Server Compact and Northwind Entity Framework Sample:");
try
{
// Establish a connection to the underlying data provider by
// using the connection string specified in the config file.
using (EntityConnection connection =
new EntityConnection("Name = NorthwindEntities"))
{
// Open the connection.
connection.Open();
// A simple query that demonstrates
// how to use Entity SQL for entities.
Console.WriteLine("\nEntity SQL Query:");
ESQL_Query(connection);
// A simple query that demonstrates
// how to use LINQ to Entities.
// A new connection is established by using the connection
// string in the App.Config file.
Console.WriteLine("\nLINQ To Entity Query:");
LINQ_To_Entity_Query();
// A simple query that demonstrates how to use ObjectContext
// on data objects with an existing connection.
Console.WriteLine("\nObject Query:");
ObjectQuery(connection);
// Close the connection.
connection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// A simple query that demonstrates how to use
// Entity SQL query for entities.
private static void ESQL_Query(EntityConnection entityConnection)
{
EntityCommand entityCommand = entityConnection.CreateCommand();
entityCommand.CommandText =
@"Select Cust.Customer_Id as Id from NorthwindEntities.Customers as Cust order by Cust.Customer_Id";
EntityDataReader entityDataReader =
entityCommand.ExecuteReader(CommandBehavior.SequentialAccess);
while (entityDataReader.Read())
{
for (int i = 0; i < entityDataReader.FieldCount; i++)
Console.Write(entityDataReader[i].ToString() + "\t");
Console.WriteLine();
}
}
// A simple LINQ query on the Customers entity set in the Northwind
// Context.
// The code example creates a new Northwind Context based on the
// settings provided in the App.Config File.
private static void LINQ_To_Entity_Query()
{
using (NorthwindEntities nwEntities = new NorthwindEntities())
{
IQueryable<string> customers =
from c in nwEntities.Customers select c.Company_Name;
foreach (String c in customers)
{
Console.WriteLine(c);
}
}
}
// The ObjectContext provides access to the collections of data used
// by applications.
// The following code shows how to open a connection to the
// ObjectContext named NorthwindEntities.
// With the application configuration file in scope the connection
// can be opened with one line of code:
// NorthwindEntities nwEntities = new NorthwindEntities(entityConnection).
private static void ObjectQuery(EntityConnection entityConnection)
{
using (NorthwindEntities nwEntities = new
NorthwindEntities(entityConnection))
{
foreach (Customers c in nwEntities.Customers)
{
Console.WriteLine(c.Company_Name);
}
}
}
}
}
Imports System.Data.EntityClient
Imports SQLCompactEDM.NorthwindModel
Module Module1
Sub Main()
Console.WriteLine("SQL Server Compact and Northwind Entity Framework Sample:")
Try
Using connection As EntityConnection = _
New EntityConnection("Name = NorthwindEntities")
' Open the connection.
connection.Open()
' A simple query that demonstrates how to use ESQL for entities.
Console.WriteLine(vbNewLine & "ESQL Query:")
ESQL_Query(connection)
' A simple query that demonstrates how to use LINQ to Entities.
' A new connection is established by using the
' connection string in the App.Config file.
Console.WriteLine(vbNewLine & "LINQ To Entity Query:")
LINQ_To_Entity_Query()
' A simple query that demonstrates how to use ObjectContext
' on data objects with an existing connection.
Console.WriteLine(vbNewLine & "Object Query:")
ObjectQuery(connection)
' Close the connection.
connection.Close()
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
' A simple query that demonstrates how to use ESQL for entities.
Private Sub ESQL_Query(ByVal entityConnection As EntityConnection)
Dim entityCommand As EntityCommand = entityConnection.CreateCommand
entityCommand.CommandText = _
"Select Cust.Customer_Id as Id from NorthwindEntities.Customers as Cust order by Cust.Customer_Id"
Dim entityDataReader As EntityDataReader = _
entityCommand.ExecuteReader(CommandBehavior.SequentialAccess)
Do While entityDataReader.Read
Dim i As Integer
For i = 0 To entityDataReader.FieldCount - 1
Console.Write((entityDataReader.Item(i).ToString & vbTab))
Next i
Console.WriteLine()
Loop
End Sub
' A simple LINQ query on the Customers entity set in the Northwind Context.
' The code example creates a new Northwind Context based on the
' settings provided in the App.Config File.
Private Sub LINQ_To_Entity_Query()
Using nwEntities As NorthwindEntities = New NorthwindEntities
Dim customers = From c In nwEntities.Customers Select c.Company_Name
For Each c In customers
Console.WriteLine(c)
Next
End Using
End Sub
' The ObjectContext provides access to the collections of data used by applications.
' The following code shows how to open a connection to the ObjectContext named NorthwindEntities.
' With the application configuration file in scope the connection can be opened with one line of code:
' NorthwindEntities nwEntities = new NorthwindEntities(entityConnection).
Private Sub ObjectQuery(ByVal entityConnection As EntityConnection)
Using nwEntities As NorthwindEntities = New NorthwindEntities(entityConnection)
Dim c As Customers
For Each c In nwEntities.Customers
Console.WriteLine(c.Company_Name)
Next
End Using
End Sub
End Module
참고 항목
개념
Entity Framework(SQL Server Compact)