运行时更改Entity Framework连接

88

我有一个 Web API 项目,引用了我的模型和数据访问层程序集。用户会看到一个登录界面,在该界面上可以选择不同的数据库。

我按如下方式构建连接字符串:

    public void Connect(Database database)
    {
        //Build an SQL connection string
        SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
        {
            DataSource = database.Server,
            InitialCatalog = database.Catalog,
            UserID = database.Username,
            Password = database.Password,
        };

        //Build an entity framework connection string
        EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
        {
            Provider = database.Provider,
            Metadata = Settings.Default.Metadata,
            ProviderConnectionString = sqlString.ToString()
        };
    }

首先,我应该如何更改数据上下文的连接?

其次,由于这是一个Web API项目,连接字符串(在上面设置)是否在用户交互过程中持久存在,还是每次都需要传递给我的数据上下文?


我加了一点点替代方案,以防它符合你的思维方式/工具箱要求。 - jim tollan
@Ivan-Mark 你是怎么解决这个部分的?另外,由于这是一个 Web API 项目,连接字符串(在上面设置)是否在用户交互期间持久存在,还是每次都应该传递给我的数据上下文? - Narendra Singh Rathore
@NarendraSinghRathore 连接字符串存储在配置文件中,数据库名称(或其他内容)作为键。用户在登录时选择数据库,并将其存储在缓存中,其中键可能是用户名。用户通过标题传递用户名发出请求,然后检索连接字符串并将其传递给数据上下文。 - Ivan-Mark Debono
@Ivan-MarkDebono,你能解释一下这个缓存吗?你是在后端使用MemoryCache或Session还是在前端存储为Cookie?谢谢! - Narendra Singh Rathore
1
@NarendraSinghRathore 单例中的 MemoryCache - Ivan-Mark Debono
13个回答

0

我想在应用程序配置中拥有多个数据源。因此,在app.config中设置了一个部分后,我替换了数据源,然后将其作为连接字符串传递给dbcontext。

//Get the key/value connection string from app config  
var sect = (NameValueCollection)ConfigurationManager.GetSection("section");  
var val = sect["New DataSource"].ToString();

//Get the original connection string with the full payload  
var entityCnxStringBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["OriginalStringBuiltByADO.Net"].ConnectionString);     

//Swap out the provider specific connection string  
entityCnxStringBuilder.ProviderConnectionString = val;

//Return the payload with the change in connection string.   
return entityCnxStringBuilder.ConnectionString;

这个问题让我花了一些时间才解决。希望我的经验能够帮助到其他人。在此之前,我把它想得过于复杂了。


0

对于 SQL Server 和 SQLite 数据库,使用以下语句:

_sqlServerDBsContext = new SqlServerDBsContext(new DbContextOptionsBuilder<SqlServerDBsContext>().UseSqlServer("Connection String to SQL DB").Options);

对于SQLite,请确保已安装Microsoft.EntityFrameworkCore.Sqlite,然后连接字符串只需为"'DataSource='+文件名"。
_sqliteDBsContext = new SqliteDBsContext(new DbContextOptionsBuilder<SqliteDBsContext>().UseSqlite("Connection String to SQLite DB").Options);

-9
Linq2SQLDataClassesDataContext db = new Linq2SQLDataClassesDataContext();

var query = from p in db.SyncAudits orderby p.SyncTime descending select p;
Console.WriteLine(query.ToString());

试试这段代码...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接