Using LINQ to SQL to create a database

I can use LINQ to create a database with some composite tables using datacontext.createDatabase (). The problem is that every time I want to add a new table to the database and use this method, I first need to delete the database and then recreate the entire database using an additional table. Obviously, this is empty content that I previously populated with tables.

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

+5
source share
3 answers

I see two ways to do this

the first

ExceuteCommand - DataContext T-SQL .

, ,

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);
    }
}
+3

, , .

EF4 - , ... (Code-First Database Evolution) EF 4.1....: - (

Microsoft (EF "" ) -

0

Nested code creates a database dynamicDatabase11and table books.

public class MyDatabse : DataContext
{
    public Table<Bookss> Bookss;
    public MyDatabse(string connection) : base(connection) { }
}

[Table(Name = "Books")]
public class Bookss
{
    [Column(IsPrimaryKey = true)]
    public string Title;
    [Column]
    public string Rating;
}
class Program
{
    static void Main(string[] args)
    {
        CreateDatabase("DynamicDatabase11");
    }
    public static void CreateDatabase(string Dbname )
    {

        MyDatabse db = new MyDatabse("ConString"+Dbname+"");
        db.CreateDatabase();
    }
}
0
source

All Articles