Linq to Sql with dynamic database

1.1k views Asked by At

I'm now creating an application which creates database in runtime.

For example: User 'A' registers to my server will be provided a database A.sdf.

After that, I want to create a connection to the newly created database file using Linq-to-SQL.

I'm wondering if I'll create that connection during design in Visual Studio, will the tables appears as classes of database context?

For example : A.sdf has a table Inventory with these columns:

  • ID
  • Name

So in Visual Studio, there will be a class named Inventory that has 2 properties.

Can anyone show me the way how to do this, please?

2

There are 2 answers

0
ArhiChief On BEST ANSWER

If you using Entity Framework and your databases are equal in their structure, you can use same domain model (EF classes) to work with all databases. All you need is to create datacontext with different connection strings. For examlple:

public class DataBaseContext : DbContext {
    public DataBaseContext (string connectionString="defaultConStrInConfig") : base(connectionString) {}
    /* some code to bind tables etc */
}

In your method:

if (userA) conStr = "<connection string for userA>";
using (var context = new DataBaseContext(conStr)){
   /* work with userA's database */
}
0
Reddog On

There are many sites on the internet with information on how to generate your Linq to SQL classes from a database.

During development, you will want to configure it to use a connection to some sort of master database with the tables designed as you require.

During runtime, you can change your connection string that is used to construct your data context such that you can use a database file located somewhere else.