ここでは、プログラムで SqlServerCe.Replication オブジェクトの AddSubscription メソッドを呼び出して、Microsoft SQL Server 2005 Compact Edition (SQL Server Compact Edition) データベースを作成する方法について学習します。SqlServerCe 名前空間の使用については、SqlServerCe 名前空間のリファレンス ドキュメントを参照してください。
Replication オブジェクトを使用して SQL Server Compact Edition データベースを作成するには
新しい Replication オブジェクトを初期化します。
SqlCeReplication repl = new SqlCeReplication();Replication オブジェクトのプロパティを設定します。これらのプロパティには、SQL Server パブリッシャに接続するために必要な情報を含めることができます。SubscriberConnectionString プロパティでは、作成するデータベースのファイル名と場所を指定します。
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf"; repl.InternetUrl = "https://www.adventure-works.com/" + "sqlmobile/sqlcesa30.dll"; repl.InternetLogin = "MyInternetLogin"; repl.InternetPassword = "<password>"; repl.Publisher = "MyPublisher"; repl.PublisherDatabase = "MyPublisherDatabase"; repl.PublisherLogin = "MyPublisherLogin"; repl.PublisherPassword = "<password>"; repl.Publication = "MyPublication"; repl.Subscriber = "MySubscriber";AddSubscription メソッドを呼び出し、AddOption.CreateDatabase を渡します。
repl.AddSubscription(AddOption.CreateDatabase);
使用例
次の例は、Replication オブジェクトを作成してデータベースとサブスクリプションのプロパティを設定し、AddSubscription メソッドを呼び出すことによって新しいデータベースを作成する方法を示しています。
SqlCeReplication repl = null;
try
{
// Instantiate and configure SqlCeReplication object
//
repl = new SqlCeReplication();
repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa30.dll";
repl.InternetLogin = "MyInternetLogin";
repl.InternetPassword = "<password>";
repl.Publisher = "MyPublisher";
repl.PublisherDatabase = "MyPublisherDatabase";
repl.PublisherLogin = "MyPublisherLogin";
repl.PublisherPassword = "<password>";
repl.Publication = "MyPublication";
repl.Subscriber = "MySubscriber";
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf";
// Create a local SQL Server Compact Edition Database subscription
//
repl.AddSubscription(AddOption.CreateDatabase);
// Synchronize to the SQL Server database
//
repl.Synchronize();
}
catch (SqlCeException)
{
// Handle errors here
//
}
finally
{
// Dispose the repl object
//
repl.Dispose();
}
Dim repl As SqlCeReplication = Nothing
Try
' Instantiate and configure SqlCeReplication object
'
repl = New SqlCeReplication()
repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa30.dll"
repl.InternetLogin = "MyInternetLogin"
repl.InternetPassword = "<password>"
repl.Publisher = "MyPublisher"
repl.PublisherDatabase = "MyPublisherDatabase"
repl.PublisherLogin = "MyPublisherLogin"
repl.PublisherPassword = "<password>"
repl.Publication = "MyPublication"
repl.Subscriber = "MySubscriber"
repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf"
' Create the local SQL Server Compact Edition Database subscription
'
repl.AddSubscription(AddOption.CreateDatabase)
' Synchronize to the SQL Server to populate the subscription
'
repl.Synchronize()
Catch
' Handle errors here
'
Finally
' Dispose the repl object
'
repl.Dispose()
End Try