qingsong
qingsong

Reputation: 785

C# add a Table<T> into an existing DataContext Instance

Is it possible that I can add Table<T> dynamiclly to an exisitng DataContext Insance in LinqToSQL?

Here is my case: I have several classsed which are using [Test] attribute to declared as Table, I want to allow user to create the corresponding SQL Server tables during run-time. I understand that If I inherit the DataContext class, I can add member Table customers; in the class and it will automaticly create such a table at the backend database. However, the problem is that whether I can add Table during run-time to a DataContext class which help me to create the correspondgin SQL Server Table corresponding to T.

Upvotes: 4

Views: 2239

Answers (3)

user1284907
user1284907

Reputation:

It is definitely possible to add tables generated at run time to the dbml. If you open the dbml file in a text editor, you can see that dbml contains the column definition. At run time you can dynamically generate this file with the new table fields and add this dbml to the .csproj project file. This will auto generate the designer classes.

<Table Name="dbo.VijaysToDos" Member="VijaysToDos">
    <Type Name="VijaysToDo">
      <Column Name="id" Type="System.Int32" DbType="Int NOT NULL" IsPrimaryKey="true" CanBeNull="false" />
      <Column Name="column1" Type="System.String" DbType="VarChar(255)" CanBeNull="true" />
      <Column Name="column2" Type="System.String" DbType="VarChar(255)" CanBeNull="true" />
      <Column Name="column3" Type="System.String" DbType="VarChar(255)" CanBeNull="true" />
      <Column Name="last_Updated" Type="System.DateTime" DbType="DateTime" CanBeNull="true" />
    </Type>
</Table>

Upvotes: 0

Mike Two
Mike Two

Reputation: 46193

You can just call GetTable<T>(); on the DataContext. It will read the attributes on T at that time.

Upvotes: 0

Arthur
Arthur

Reputation: 8129

I don't think that this is possible. Linq2Sql reads Meta information from your Attributes and store them in a cache - for all instances of your context.

The only chance you have is to generate those classes in Memory and then emit them into a new AppDomain. Sounds hard, but it isn't. But how do you want to access those classes? Reflection?

Upvotes: 1

Related Questions