在运行时使用表创建SQL Server CE DataContext [英] Creating SQL Server CE DataContext with Tables at runtime

查看:139
本文介绍了在运行时使用表创建SQL Server CE DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Windows Phone 8构建一个需要本地数据库的库.这是我对LINQ-to-SQL如何工作和创建数据库的理解:

I am building a library for Windows Phone 8 which requires local databases. Here is my understanding of how the LINQ-to-SQL works and creates database:

  • DataContext对象是从相应的类创建的.
  • 调用CreateDatabase()方法时,它将从DataContext对象中读取连接字符串和Table类型的成员.
  • 该方法在给定位置创建数据库,并创建与DataContext对象的成员相对应的表.
  • DataContext object is created from the corresponding class.
  • When CreateDatabase() method is called, it reads the connection string and the members of type Table from the DataContext object.
  • The method creates database at given location and creates tables corresponding to the members of DataContext object.

现在,必须严格键入DataContext类.在构建库时,我不知道用户将需要哪些表.显然,我不能使用硬类型的DataContext.而且,在这种情况下CreateTable()方法不存在.如果我只是开始使用GetTable方法,则会出现Table does not exist错误.

Now, the DataContext class has to be hard typed. As I am building a library, I wouldn't know which tables the user will need. Obviously, I cannot use the hard typed DataContext. Moreover, CreateTable() method doesn't exist in this scenario. If I simply start using GetTable method, I get Table does not exist error.

问题是,如何在不使用硬类型DataContext的情况下获得创建表?

The question is, how do I get create tables without using a hard typed DataContext?

PS:我的情况有点类似于这个.

P.S.: My situation is sort of similar to this.

推荐答案

在Windows Phone的LINQ-to-SQL方案中,无法在DataContext初始化后将表添加到其中.在我的情况下,解决方案是接受来自库用户的整个DataContext,如下所示:

In the scenario of LINQ-to-SQL for Windows Phone, it is not possible to add tables to the DataContext after it is initialized. In my case, solution was to accept the whole DataContext from the user of library as follows:

首先,您提供一个可以从中派生用户的基类.

First, you provide a base class from which users can derive.

public class DataContextBase : DataContext
{
    public DataContextBase(string connectionString) : base(connectionString)
    { }

    //Tables for library's internal workings.
    public Table<SyncTimeStamp> SyncTimeStamps;
}

然后,用户可以在配置库时传递派生类.库可以接受这是方法参数:

Then user can pass the derived class while configuring the library. Library may accept this is method parameter:

public async void ConfigureSQLCE<T>(T mainDataContext) where T : DataContextBase
{   
    //Do whatever with it. MainDB is a dynamic here!
    MainDB = mainDataContext;
}

这篇关于在运行时使用表创建SQL Server CE DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆