[英]Passing Connection String as a parameter in constructor in Code First Entity Framework
I'm passing the Connection String to my Entity Classes via parameter in the constructor, like this: 我正在通过构造函数中的参数将连接字符串传递给我的实体类,如下所示:
public class Site : ISite
{
private readonly string _connectionString;
public Site(string connectionString)
{
_connectionString = connectionString;
}
An Exception is thrown when I query the Database like this: 当我像这样查询数据库时,将引发异常:
var site = db.Sites.FirstOrDefault(s => s.Name.Equals(name));
The Exception: 例外:
InvalidOperationException: The class 'AuctionSite.Site' has no parameterless constructor.
According to the post I found on this thread the documentation states that: 根据我在该线程上发现的帖子,文档指出:
There must be a parameterless constructor
必须有一个无参数的构造函数
If I create a parameterless constructor the Connection String won't be set and when I create a context inside a method, for example: 如果创建无参数的构造函数,则不会设置连接字符串,并且在方法内部创建上下文时,例如:
public IEnumerable<IUser> GetUsers()
{
using (var db = new SiteContext(_connectionString))
{
return db.Users;
}
}
_connectionString
will be null
and will fail when calling base constructor of DbContext. _connectionString
将为null
并且在调用DbContext的基本构造函数时将失败。
How should I pass the Connection String to my Entity Classes if not through the constructor? 如果不通过构造函数,应如何将连接字符串传递给实体类?
Is there a better way to do this? 有一个更好的方法吗? Maybe by materializing the Entity with my connection string as a parameter or with a better query?
也许通过将连接字符串作为参数或更好的查询来实现实体?
There is nothing that stops you from having two constructors: 没有什么可以阻止您拥有两个构造函数:
public Site(string connectionString)
{
_connectionString = connectionString;
}
public Site()
{
}
It looks like you might be confusing Site the entity and SiteContext the DbContext. 看来您可能会混淆Site实体和SiteContext以及DbContext。 Site the entity needs the to have a parameterless constructor.
实体需要拥有无参数构造函数的站点。 SiteContext is the thing which deals with the connection string.
SiteContext是处理连接字符串的事物。 The entities do not need to know about the connection string, in fact, they shouldn't know they are related to the database at all.
实体不需要知道连接字符串,实际上,它们根本不需要知道它们与数据库有关。
Additionally the code you have 此外,您拥有的代码
public IEnumerable<IUser> GetUsers()
{
using (var db = new SiteContext(_connectionString))
{
return db.Users;
}
}
Will set the connection string just fine. 将设置连接字符串就好了。 The constructor which matches the arguments, in this case a string, is the one which is called.
与参数匹配的构造函数(在本例中为字符串)就是被调用的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.