Creating SQL Server CE DataContext with Tables at runtime

爷,独闯天下 提交于 2019-12-12 00:35:05

问题


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 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.

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.

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

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


回答1:


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;
}


来源:https://stackoverflow.com/questions/19082512/creating-sql-server-ce-datacontext-with-tables-at-runtime

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