Click here to Skip to main content
15,884,936 members
Articles / Programming Languages / C# 4.0

Dynamic Table Mapping for LINQ-to-SQL

Rate me:
Please Sign up or sign in to vote.
5.00/5 (17 votes)
21 May 2012CPOL7 min read 225.2K   2.3K   40  
Dynamic table mapping for LINQ-to-SQL, suitable for data horizontal partitioning (Shard).
using System;
using System.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Prototype.NamedTable
{
    /// <summary>
    /// Sets of method to prepare a test database
    /// </summary>
    [TestClass]
    public class Preparation
    {
        public const string SQLTest = @"Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False";

        [TestMethod]
        public void RebuildDatabase()
        {
            var connection = new SqlConnection(SQLTest);
            connection.Open();

            var command = connection.CreateCommand();
            command.CommandText = "drop table result2011";
            try { command.ExecuteNonQuery(); }
            catch (Exception) { }

            command.CommandText = "create table result2011 (id int, name varchar(50), value float)";
            command.ExecuteNonQuery();

            for (int i = 0; i < 20; i++)
            {
                command.CommandText =
                    string.Format(
                        "insert into result2011(id, name, value) values ({0},'{1}',{2})",
                        i + 1, "2011_" + i, i * 1.395896 % 100);
                command.ExecuteNonQuery();
            }

            command.CommandText = "drop table result2012";
            try { command.ExecuteNonQuery(); }
            catch (Exception) { }

            command.CommandText = "create table result2012 (id int, name varchar(50), value float)";
            command.ExecuteNonQuery();

            for (int i = 0; i < 10; i++)
            {
                command.CommandText =
                    string.Format(
                        "insert into result2012(id, name, value) values ({0},'{1}', {2})",
                        i + 100, "2012_" + i, i * 20.39548 % 100);
                command.ExecuteNonQuery();
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) 3PLearning
Australia Australia
Lead Developer, MMO Game Company
Testor, Microsoft

Comments and Discussions