Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to SQL to create a database

Tags:

c#

linq-to-sql

I can use LINQ to create a database with some constituent tables using datacontext.createDatabase(). The problem is, each time I want to add a new table to the database and use this method, I have to delete the database first and then recreate the whole database with the additional table. This obviously blanks all the contents I had previously populated the tables with.

Is there a way to simply add the new table into the database without recreating it each time from scratch?

like image 700
Deepanjan Nag Avatar asked Oct 10 '22 19:10

Deepanjan Nag


1 Answers

I see two ways to do that

first

you can use the ExceuteCommand -method of the DataContext to run some T-SQL statements for creating tables.

and second

you can use this hack function if you have mapped table type, as suggested here

public void CreateTable(Type linqTableClass)
{
    using (var tempDc = new DmsDataContext())
    {
        var metaTable = tempDc.Mapping.GetTable(linqTableClass);
        var typeName = "System.Data.Linq.SqlClient.SqlBuilder";
        var type = typeof(DataContext).Assembly.GetType(typeName);
        var bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
        var sql = type.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
        var sqlAsString = sql.ToString();
        tempDc.ExecuteCommand(sqlAsString);
    }
}
like image 154
Arsen Mkrtchyan Avatar answered Nov 14 '22 23:11

Arsen Mkrtchyan