C# 添加一个 Table到现有的 DataContext 实例中
我是否可以将 Table
动态添加到 LinqToSQL 中现有的 DataContext 实例中?
这是我的案例: 我有几个类使用 [Test] 属性声明为表,我想允许用户在运行时创建相应的 SQL Server 表。我明白如果我继承 DataContext 类,我可以添加成员 表顾客; 在类中,它会自动在后端数据库中创建这样的表。 但是,问题是我是否可以在运行时将 Table 添加到 DataContext 类,以帮助我创建与 T 对应的相应 SQL Server 表。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这是不可能的。 Linq2Sql 从您的属性中读取元信息并将它们存储在缓存中 - 对于您的上下文的所有实例。
您唯一的机会是在内存中生成这些类,然后将它们发送到新 AppDomain 中。听起来很难,但事实并非如此。但是您想如何访问这些类呢?反射?
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?
您只需调用 GetTable();在数据上下文上。此时它将读取 T 上的属性。
You can just call GetTable<T>(); on the DataContext. It will read the attributes on T at that time.
绝对可以将运行时生成的表添加到 dbml。如果在文本编辑器中打开 dbml 文件,您可以看到 dbml 包含列定义。在运行时,您可以使用新的表字段动态生成此文件,并将此 dbml 添加到
.csproj
项目文件中。这将自动生成设计器类。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.