Visual Studio を使用して SQL Server CE データベースで外部キー関係を作成する
SQL Server CE で外部キー関係を作成する方法
SQL Server CE (Compact Edition) は、軽量なデータベースエンジンであり、デスクトップアプリケーションやモバイルアプリケーションで使用するために設計されています。
このチュートリアルでは、Visual Studio を使用して SQL Server CE データベースで外部キー関係を作成する方法を説明します。
手順
using System;
using System.Data.SQLite;
namespace CreateForeignKeyRelationship
{
class Program
{
static void Main(string[] args)
{
// データベース接続文字列
string connectionString = @"Data Source=MyDatabase.sdf";
// テーブル作成
CreateTable(connectionString);
// 外部キー関係作成
CreateForeignKeyRelationship(connectionString);
// データ挿入
InsertData(connectionString);
// データ読み取り
ReadData(connectionString);
}
static void CreateTable(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
CREATE TABLE Customers (
CustomerId INTEGER PRIMARY KEY AUTOINCREMENT,
FirstName TEXT,
LastName TEXT
);
CREATE TABLE Orders (
OrderId INTEGER PRIMARY KEY AUTOINCREMENT,
CustomerId INTEGER,
OrderDate DATETIME,
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
);
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void CreateForeignKeyRelationship(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customers(CustomerId)
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void InsertData(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
INSERT INTO Customers (FirstName, LastName)
VALUES ('John', 'Doe'), ('Jane', 'Doe');
INSERT INTO Orders (CustomerId, OrderDate)
VALUES (1, '2023-01-01'), (2, '2023-02-01');
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void ReadData(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
SELECT
c.FirstName,
c.LastName,
o.OrderDate
FROM Customers c
INNER JOIN Orders o ON c.CustomerId = o.CustomerId;
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} - {2}", reader["FirstName"], reader["LastName"], reader["OrderDate"]);
}
}
}
}
}
}
}
このコードは、次のことを行います。
Customers
とOrders
という名前の 2 つのテーブルを作成します。Customers
テーブルのCustomerId
列は主キーです。Orders
テーブルのCustomerId
列は外部キーであり、Customers
using System;
using System.Data.SQLite;
namespace CreateForeignKeyRelationship
{
class Program
{
static void Main(string[] args)
{
// データベース接続文字列
string connectionString = @"Data Source=MyDatabase.sdf";
// テーブル作成
CreateTable(connectionString);
// 外部キー関係作成
CreateForeignKeyRelationship(connectionString);
// データ挿入
InsertData(connectionString);
// データ読み取り
ReadData(connectionString);
}
static void CreateTable(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
CREATE TABLE Customers (
CustomerId INTEGER PRIMARY KEY AUTOINCREMENT,
FirstName TEXT,
LastName TEXT
);
CREATE TABLE Orders (
OrderId INTEGER PRIMARY KEY AUTOINCREMENT,
CustomerId INTEGER,
OrderDate DATETIME,
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
);
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void CreateForeignKeyRelationship(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customers(CustomerId)
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void InsertData(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
INSERT INTO Customers (FirstName, LastName)
VALUES ('John', 'Doe'), ('Jane', 'Doe');
INSERT INTO Orders (CustomerId, OrderDate)
VALUES (1, '2023-01-01'), (2, '2023-02-01');
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
static void ReadData(string connectionString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string sql = @"
SELECT
c.FirstName,
c.LastName,
o.OrderDate
FROM Customers c
INNER JOIN Orders o ON c.CustomerId = o.CustomerId;
";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} - {2}", reader["FirstName"], reader["LastName"], reader["OrderDate"]);
}
}
}
}
}
}
}
- コードは、
Customers
テーブルとOrders
テーブルにデータを追加します。
実行方法
- Program.cs ファイルに上記のコードを追加します。
出力
John Doe - 2023-01-01
Jane Doe - 2023-02-01
補足
- このコードは、SQL Server CE 4.0 で動作します。
- 詳細については、
SQL Server CE で外部キー関係を作成する他の方法
SQL Server Management Studio (SSMS) を使用する
SSMS は、SQL Server データベースを管理するためのツールです。SSMS を使用して外部キー関係を作成するには、次の手順に従います。
- SSMS を起動し、SQL Server CE データベースに接続します。
- オブジェクトエクスプローラーで、テーブル フォルダーを展開します。
- 外部キー関係を作成するテーブルを選択します。
- デザイナー タブをクリックします。
- 関係 ウィンドウで、新しい関係 をクリックします。
- 主キーテーブル ドロップダウンリストから、外部キーが参照するテーブルを選択します。
- OK をクリックします。
T-SQL を使用する
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customers(CustomerId)
Visual Studio には、データベースを操作するためのツールがいくつか含まれています。これらのツールを使用して外部キー関係を作成するには、次の手順に従います。
- Visual Studio で、データベースプロジェクトを開きます。
- プロパティ ウィンドウを開きます。
- 関係 プロパティページを選択します。
どの方法を使用しても、同じ結果が得られます。自分に最も適した方法を選択してください。
database visual-studio sql-server-ce