Linq to Sql与动态数据库

Linq to Sql with dynamic database
2020-10-17
  •  译文(汉语)
  •  原文(英语)

我现在正在创建一个在运行时创建数据库的应用程序.

例如:向我的服务器注册的用户"A"将获得一个数据库A.sdf.

之后,我想使用Linq-to-SQL创建到新创建的数据库文件的连接.

我想知道是否在Visual Studio设计期间创建该连接,这些表会显示为数据库上下文类吗?

例如:A.sdf有一个 Inventory包含以下列的表:

  • ID
  • 名称

因此,在Visual Studio中,将存在一个Inventory具有2个属性的名为的类.

有人可以告诉我如何做到这一点吗?

解决过程1

如果使用Entity Framework,并且数据库的结构相同,则可以使用相同的域模型(EF类)来处理所有数据库.您需要做的是使用不同的连接字符串创建数据上下文.例如:

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

在您的方法中:

if (userA) conStr = "<connection string for userA>";
using (var context = new DataBaseContext(conStr)){
   /* work with userA's database */
}
解决过程2

互联网上有许多网站,其中包含有关如何从数据库生成Linq to SQL类的信息.

在开发过程中,您将需要对其进行配置,以使用与某种主数据库的连接以及根据需要设计的表.

在运行时,您可以更改用于构造数据上下文的连接字符串,以便可以使用其他位置的数据库文件.

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?

Solutions1

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 */
}
Solutions2

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.

转载于:https://stackoverflow.com/questions/30859053/linq-to-sql-with-dynamic-database

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入