实体框架6在代码中设置了连接字符串
本文关键字:设置 连接 字符串 代码 框架 实体 | 更新日期: 2023-09-27 18:27:13
我有一个dll,它使用Entity Framework 6来执行一些数据库操作。我使用的是数据库优先的方法。模型和与实体框架有关的一切,如App.config中的连接字符串,都是通过Visual Studio中的向导创建的。
因此,我编译了dll,并将其与相应的.config放在使用dll的应用程序所期望的文件夹中
在进行实际的数据库调用之前,一切都很好。在那里我得到了错误:
找不到MyDatabaseEntity 的连接字符串
正如我所说,自动生成的连接字符串在dll的配置文件中。我无法更改应用程序的App.config。但是应用程序会移交一个对象,该对象具有我自己构建连接字符串所需的所有信息。因此,我正在寻找一种在不依赖配置文件的情况下在代码中设置连接字符串的方法。不过,我找到的所有数据库优先方法的教程都使用这种方法。我在这里发现了一篇帖子,上面说在创建类似的对象时,只需将连接字符串作为参数
MyDatabaseEntities = new MyDatabaseEntities(dbConnect);
但是"MyDatabaseEntities"没有采用任何参数的构造函数
public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities()
: base("name=MyDatabaseEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<MyTable> MyTable { get; set; }
}
怎么样:
public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities(string connectionString)
: base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<MyTable> MyTable { get; set; }
}
然后像以前一样初始化数据库:
string myConnectionString = "...";
MyDatabaseEntities = new MyDatabaseEntities(myConnectionString);
我也遇到了类似的问题。我的Edmx和App.Config在另一个项目中。我的启动项目不同,有3个不同的连接字符串,我们需要根据环境随时选择一个。因此无法使用固定的连接字符串。我使用相同的命名空间创建了Context.cs的部分类重载。以下是我默认的Context.cs;
namespace CW.Repository.DBModel
{
public partial class CWEntities : DbContext
{
public CWEntities()
: base("name=CWEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
...
...
}
}
我的部分班级超负荷;
namespace CW.Repository.DBModel
{
public partial class CWEntities : DbContext
{
public CWEntities(string ConnectionString)
: base(ConnectionString)
{
}
}
}
最后,由于我的连接字符串不适用于EF,我将它们转换为EF连接字符串。
public static string GetEntityConnectionString(string connectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// WARNING
// Check app config and set the appropriate DBModel
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = connectionString + ";MultipleActiveResultSets=True;App=EntityFramework;";
entityBuilder.Metadata = @"res://*/DBModel.CWDB.csdl|res://*/DBModel.CWDB.ssdl|res://*/DBModel.CWDB.msl";
return entityBuilder.ToString();
}
最后,调用
var Entity = new CWEntities(CWUtilities.GetEntityConnectionString(ConnectionString));
我使用下面的代码得到了这个解决方案,我可以使用C#代码硬编码连接字符串,而无需使用配置文件。
public class SingleConnection
{
private SingleConnection() { }
private static SingleConnection _ConsString = null;
private String _String = null;
public static string ConString
{
get
{
if (_ConsString == null)
{
_ConsString = new SingleConnection { _String = SingleConnection.Connect() };
return _ConsString._String;
}
else
return _ConsString._String;
}
}
public static string Connect()
{
//Build an SQL connection string
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = "SIPL35''SQL2016".ToString(), // Server name
InitialCatalog = "Join8ShopDB", //Database
UserID = "Sa", //Username
Password = "Sa123!@#", //Password
};
//Build an Entity Framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
Metadata = "res://*/ShopModel.csdl|res://*/ShopModel.ssdl|res://*/ShopModel.msl",
ProviderConnectionString = @"data source=SIPL35'SQL2016;initial catalog=Join8ShopDB2;user id=Sa;password=Sa123!@#;"// sqlString.ToString()
};
return entityString.ConnectionString;
}
并使用DbContext使用如下:
Join8ShopDBEntities dbContext = new Join8ShopDBEntities(SingleConnection.ConString);
非常感谢。我对代码第一EF6几乎没有什么改变。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data
{
public class SingleConnection
{
private SingleConnection() { }
private static SingleConnection _ConsString = null;
private String _String = null;
public static string ConString
{
get
{
if (_ConsString == null)
{
_ConsString = new SingleConnection { _String = SingleConnection.Connect() };
return _ConsString._String;
}
else
return _ConsString._String;
}
}
public static string Connect()
{
string conString = ConfigurationManager.ConnectionStrings["YourConnectionStringsName"].ConnectionString;
if (conString.ToLower().StartsWith("metadata="))
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(conString);
conString = efBuilder.ProviderConnectionString;
}
SqlConnectionStringBuilder cns = new SqlConnectionStringBuilder(conString);
string dataSource = cns.DataSource;
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = cns.DataSource, // Server name
InitialCatalog = cns.InitialCatalog, //Database
UserID = cns.UserID, //Username
Password = cns.Password, //Password,
MultipleActiveResultSets = true,
ApplicationName = "EntityFramework",
};
//Build an Entity Framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
Metadata = "res://*",
ProviderConnectionString = sqlString.ToString()
};
return entityString.ConnectionString;
}
}
}
您可以使用singleton模式。例如
private YouurDBContext context;
public YouurDBContext Context
{
get
{
if (context==null)
{
context = new YouurDBContext();
}
return context;
}
set { context = value; }
}