장점은 프로그래밍 적으로 연결 문자열을 만들기 때문에 개발이 더 동적이다.

필요한 라이브러리 : EntityFramework

클래스 : SqlConnectionStringBuilder,EntityConnectionStringBuilder

필요한 문자열 값

ProviderName : System.Data.SqlClient

ServerName : 서버 이름 

DatabaseName : 사용할 데이터 베이스 이름

Metadata = 예) "res://*/LocalModel.csdl|res://*/LocalModel.ssdl|res://*/LocalModel.msl";

이렇게 준비 하면 이제 동적으로 소스 상에서 연결 문자열을 만들 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 class Program
    {
        static void Main(string[] args)
        {
 
            // Specify the provider name, server and database.
            string providerName = "System.Data.SqlClient";
            string serverName = @".\SQLEXPRESS";
            string databaseName = "eLearning";
 
            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
                new SqlConnectionStringBuilder();
 
            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = true;
 
            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();
 
            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();
 
            //Set the provider name.
            entityBuilder.Provider = providerName;
 
            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;
 
            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/LocalModel.csdl|res://*/LocalModel.ssdl|res://*/LocalModel.msl";
 
            Console.WriteLine(entityBuilder.ToString());
 
            using (EntityConnection conn =
                new EntityConnection(entityBuilder.ToString()))
            {
                conn.Open();
                Console.WriteLine("Just testing the connection.");
                conn.Close();
            }
 
        }
    }
cs


여기서 만든 EntityConnectionStringBuilder 객체를 EntityConnection 으로 인자값을 넘겨주면 된다.

1
2
3
4
using (SampleEntities _entity = new SampleEntities(EntityConnectionStringBuilder 인자값))
{
}
 
cs


Entity 객체를 사용할 때 데이터베이스 서버가 바뀔 수 있다. 하지만 여기서 중요한건 Schema는 바뀌면 안된다는 것이다.

Schema를 바꾼 데이터베이스를 연결했을 경우 분명 에러가 나타날 것이다.


Sample.

ConnectionStringSample.zip


Posted by Hoya0415
,