C # add table <T> to existing instance of DataContext

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

Here is my case: I have several classes that use the [Test] attribute to declare as Table, I want to allow the user to create the appropriate SQL Server tables at run time. I understand that if I inherit the DataContext class, I can add a member to the Clients table; in the class and it will automatically create such a table in the backend database. However, the problem is whether I can add the table at run time to the DataContext class, which will help me create the corresponding SQL Server table corresponding to T.

+4
source share
3 answers

I do not think that's possible. Linq2Sql reads meta information from your attributes and stores them in the cache - for all instances of your context.

The only chance you have is to generate these classes in memory and then emit them into the new AppDomain. It sounds complicated, but it is not. But how do you want to access these classes? Reflection?

+1
source

You can just call GetTable <T> (); in a DataContext. He will read attributes on T at this time.

0
source

You can definitely add tables generated at runtime in dbml. If you open the dbml file in a text editor, you will see that dbml contains a column definition. At run time, you can dynamically generate this file with new table fields and add this dbml to the .csproj project .csproj . This will automatically generate 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> 
0
source

All Articles