简体   繁体   English

EntityFramework在哪里获得到本地数据库的连接字符串?

[英]Where does EntityFramework get the connection string to my local database?

I have created a web form that is a registration form using Identity. 我创建了一个Web表单,它是使用Identity的注册表单。 The form calls code behind that looks like this: 表单调用后面的代码,如下所示:

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();
    }
}

And my web config file is this: 我的网络配置文件是这样的:

<?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>

I also have MS SQL Express installed on my machine. 我的计算机上也安装了MS SQL Express。 When i use the form the app creates a database in SQLExpress called DefaultConnection. 当我使用表单时,应用程序会在SQLExpress中创建一个名为DefaultConnection的数据库。

My question is how does entity/identity/.net know about my database at all, since I don't have the connection string written anywhere explicitly? 我的问题是,因为我没有在任何地方显式写入连接字符串,所以entity / identity / .net怎么完全了解我的数据库?

If this is somehow a feature of 'convention over configuration' then how can I explicitly direct entity to a different database? 如果这是“按惯例进行约定”的功能,那么如何将实体显式定向到其他数据库?

Edit: 编辑:

I have tried adding 我尝试添加

<add name="MyConnection"
  connectionString="[the connection string];TrustServerCertificate=False"
  providerName="System.Data.SqlClient" />`

to the connection strings and updated my create user code: 到连接字符串并更新了我的创建用户代码:

...
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);
...

but this threw a InvalidOperationException with the following message: 但这引发了InvalidOperationException与以下消息:

Additional information: The entity type IdentityUser is not part of the model for the current context.

Last Edit: 最后编辑:

Found out how to avoid the exception, changed this: 发现如何避免异常,对此进行了更改:

var context = new System.Data.Entity.DbContext(connString);

into this: 到这个:

var context = new Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext(connString);

By convention a local database will be created on your local SQL Server instance. 按照约定,将在本地SQL Server实例上创建一个本地数据库。

See: Code First to a New Database - MSDN 请参阅: 代码优先到新数据库-MSDN

By convention DbContext has created a database for you. 按照约定,DbContext为您创建了一个数据库。

  • 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 如果本地SQL Express实例可用(默认情况下随Visual Studio 2010安装),则Code First已在该实例上创建数据库
  • If SQL Express isn't available then Code First will try and use LocalDb (installed by default with Visual Studio 2012) 如果无法使用SQL Express,则Code First将尝试并使用LocalDb(默认情况下与Visual Studio 2012一起安装)
  • The database is named after the fully qualified name of the derived context 数据库以派生上下文的完全限定名称命名

You can over come it by specifying an explicit connection string in web.config like: 您可以通过在web.config指定一个显式的连接字符串来web.config例如:

<configuration>
  <connectionStrings>
    <add name="MyDBContext"
         connectionString="Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Here remember to change the name to the class that is extending DbContext in your code. 在这里,请记住将名称更改为在代码中扩展DbContext的类。

So for example if you are extending DbContext as: 因此,例如,如果您将DbContext扩展为:

public class MyDBContext : DbContext

then use MyDBContext as key for connection string in the configuration. 然后使用MyDBContext作为配置中连接字符串的键。

or off course you can pass the connection string in the constructor: 当然也可以在构造函数中传递连接字符串:

namespace MyCodeFirstProject 
{     
    public class MyDBContext: DbContext     
    {         
        public MyDBContext() : 
            base("Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName") {}
    }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 神秘的EntityFramework数据库在哪里? - Where is the mysterious EntityFramework database? EntityFramework 6基于数据库的连接字符串的基于代码的配置 - EntityFramework 6 Code-based configuration of connection string for database-first 为EntityFramework6.Npgsql指定数据库连接字符串-代码优先 - Specifying database connection string for EntityFramework6.Npgsql - Code First 找不到我的数据库文件和连接字符串所在的位置? - Unable to find where my database file and connection string is located? 多数据库连接字符串:将其存储在我的应用程序中的位置 - Multi-database connection string: where store it in my application 本地数据库的连接字符串不起作用 - Connection string for local database not working 本地.m​​df数据库连接字符串 - local .mdf database connection string 通过EntityFramework和MVC到SQL的连接字符串 - Connection string to SQL by EntityFramework and MVC 在实体框架中找不到连接字符串 - could not find connection string in entityframework Visual Studio安装 - 安装后应该在哪里指向本地数据库连接字符串? - Visual Studio Install - Post-install where should I point local database connection string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM