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

我的未来我决定 提交于 2019-12-23 14:58:09

问题


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.


回答1:


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?




回答2:


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




回答3:


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>


来源:https://stackoverflow.com/questions/1470106/c-sharp-add-a-tablet-into-an-existing-datacontext-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!