EntityFramework 从哪里获取本地数据库的连接字符串?
Where does EntityFramework get the connection string to my local database?
我创建了一个 Web 表单,它是一个使用 Identity 的注册表单。表单调用背后的代码如下所示:
protected void CreateUser_Click(object sender, EventArgs e)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
}
else
{
StatusMessage.Text = result.Errors.FirstOrDefault();
}
}
我的网络配置文件是这样的:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section
name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<system.web>
<authentication mode="Forms" />
<roleManager enabled="true" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
我的机器上也安装了 MS SQL Express。当我使用表单时,应用程序会在 SQLExpress 中创建一个名为 DefaultConnection 的数据库。
我的问题是 entity/identity/.net 是怎么知道我的数据库的,因为我没有在任何地方显式地写连接字符串?
如果这是 'convention over configuration' 的某种特性,那么我如何才能明确地将实体定向到不同的数据库?
编辑:
我试过添加
<add name="MyConnection"
connectionString="[the connection string];TrustServerCertificate=False"
providerName="System.Data.SqlClient" />`
到连接字符串并更新了我的创建用户代码:
...
var connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
var context = new System.Data.Entity.DbContext(connString);
var userStore = new UserStore<IdentityUser>(context);
var manager = new UserManager<IdentityUser>(userStore);
...
但这引发了 InvalidOperationException
并显示以下消息:
Additional information: The entity type IdentityUser is not part of the model for the current context.
最后编辑:
发现了如何避免异常,改变了这个:
var context = new System.Data.Entity.DbContext(connString);
进入这个:
var context = new Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext(connString);
按照惯例,本地数据库将在您的本地 SQL 服务器实例上创建。
参见:Code First to a New Database - MSDN
By convention DbContext has created a database for you.
- If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance
- If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012)
- The database is named after the fully qualified name of the derived context
您可以通过在 web.config
中指定显式连接字符串来克服它,例如:
<configuration>
<connectionStrings>
<add name="MyDBContext"
connectionString="Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
这里记得把名字改成扩展DbContext
的class
例如,如果您将 DbContext
扩展为:
public class MyDBContext : DbContext
然后使用 MyDBContext
作为配置中连接字符串的键。
当然你也可以在构造函数中传递连接字符串:
namespace MyCodeFirstProject
{
public class MyDBContext: DbContext
{
public MyDBContext() :
base("Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName") {}
}
}
我创建了一个 Web 表单,它是一个使用 Identity 的注册表单。表单调用背后的代码如下所示:
protected void CreateUser_Click(object sender, EventArgs e)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
}
else
{
StatusMessage.Text = result.Errors.FirstOrDefault();
}
}
我的网络配置文件是这样的:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section
name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<system.web>
<authentication mode="Forms" />
<roleManager enabled="true" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
我的机器上也安装了 MS SQL Express。当我使用表单时,应用程序会在 SQLExpress 中创建一个名为 DefaultConnection 的数据库。
我的问题是 entity/identity/.net 是怎么知道我的数据库的,因为我没有在任何地方显式地写连接字符串?
如果这是 'convention over configuration' 的某种特性,那么我如何才能明确地将实体定向到不同的数据库?
编辑:
我试过添加
<add name="MyConnection"
connectionString="[the connection string];TrustServerCertificate=False"
providerName="System.Data.SqlClient" />`
到连接字符串并更新了我的创建用户代码:
...
var connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
var context = new System.Data.Entity.DbContext(connString);
var userStore = new UserStore<IdentityUser>(context);
var manager = new UserManager<IdentityUser>(userStore);
...
但这引发了 InvalidOperationException
并显示以下消息:
Additional information: The entity type IdentityUser is not part of the model for the current context.
最后编辑:
发现了如何避免异常,改变了这个:
var context = new System.Data.Entity.DbContext(connString);
进入这个:
var context = new Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext(connString);
按照惯例,本地数据库将在您的本地 SQL 服务器实例上创建。
参见:Code First to a New Database - MSDN
By convention DbContext has created a database for you.
- If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance
- If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012)
- The database is named after the fully qualified name of the derived context
您可以通过在 web.config
中指定显式连接字符串来克服它,例如:
<configuration>
<connectionStrings>
<add name="MyDBContext"
connectionString="Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
这里记得把名字改成扩展DbContext
的class
例如,如果您将 DbContext
扩展为:
public class MyDBContext : DbContext
然后使用 MyDBContext
作为配置中连接字符串的键。
当然你也可以在构造函数中传递连接字符串:
namespace MyCodeFirstProject
{
public class MyDBContext: DbContext
{
public MyDBContext() :
base("Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName") {}
}
}