LINQ to SQL で動的にデータベースとテーブルを作成できる!

LINQ to SQL の DataContext を使えば、簡単にデータベースを作成できます。しかも、同時にテーブルまで作成してくれます。これはウレシイ。

using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;

namespace LinqToSqlSample
{
    [Table(Name = "users")]
    public class User
    {
        [Column(Name = "id", DbType = "UniqueIdentifier NOT NULL", IsPrimaryKey = true)]
        public Guid Id { get; set; }

        [Column(Name = "name", DbType = "NVarChar(MAX) NOT NULL", CanBeNull = false)]
        public string Name { get; set; }

        [Column(Name = "password", DbType = "NVarChar(MAX) NOT NULL", CanBeNull = false)]
        public string Password { get; set; }
    }

    [DatabaseAttribute(Name = "LinqToSqlSample")]
    public partial class UsersDataContext : DataContext
    {
        private static MappingSource mappingSource = new AttributeMappingSource();

        public UsersDataContext(string connection) :
            base(connection, mappingSource)
        {
        }

        public Table<User> Users
        {
            get
            {
                return this.GetTable<User>();
            }
        }
    }

    class Program
    { 
        static void Main(string[] args)
        {
            // 接続文字列を作成
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "(local)";
            builder.IntegratedSecurity = true;

            using (UsersDataContext context = new UsersDataContext(builder.ToString()))
            {
                // 古いデータべースを削除
                if (context.DatabaseExists())
                {
                    context.DeleteDatabase();
                }

                // 新しいデータベースを作成
                // テーブルも一緒に作成される
                context.CreateDatabase();

                // Users テーブルにデータを詰める
                User user = new User();
                user.Id = Guid.NewGuid();
                user.Name = "Foo";
                user.Password = "Bar";
                context.Users.InsertOnSubmit(user);
                context.SubmitChanges();
            }

            Console.ReadLine();
        }
    }
}

テスト開始時にテストデータベースを作成し、テスト終了時に削除、といった処理が簡単に実現できますね。