【问题标题】:How to set the database name in the connection string with Entity Framework 5如何使用 Entity Framework 5 在连接字符串中设置数据库名称
【发布时间】:2014-08-28 20:09:50
【问题描述】:

所以我有两个项目的解决方案。第一个项目应该充当Data Access Layer,所以在app.config 文件中我有这个:

<connectionStrings>
 <add name="BloggingContextCF" 
   connectionString="provider=System.Data.SqlClient;
   provider connection string=&quot;
   data source=*****\SQLEXPRESS;
   initial catalog=CodeFirst.Blogging;
   integrated security=True;
   MultipleActiveResultSets=True;
   App=EntityFramework&quot;" 
   providerName="System.Data.EntityClient" />

第二个项目是ASP.NET Web Forms 项目,我删除了指向(local) 实例的默认连接字符串,只留下一个连接字符串,即来自第一个Data Access Layer 项目的连接字符串。这实际上有效并且数据库是在我的SQL 2008 R2 服务器上创建的,但不是所需(和预期的)数据库名称 - CodeFirst.Blogging 名称是 DataAccessLayer.BloggingContextCF 其中DataAccessLayer 是项目的名称和BloggingContextCF是扩展DbContext 的类。

我需要在我的连接字符串中进行哪些更改才能获得所需的名称?

【问题讨论】:

    标签: c# asp.net entity-framework


    【解决方案1】:

    试试

    public BloggingContextCF ():base("CodeFirst.Blogging") {}
    

    【讨论】:

    • 嗨。你的建议有效。但我真的希望从连接字符串中获取名称并在源代码中硬编码。知道我该怎么做>
    • entityframeworktutorial.net/code-first/… .. 但这或多或少只是告诉你 Ashish Rajput 写了什么
    • 只有一件事我无法理解为什么在三个示例中的两个示例中我们使用构造函数 - public Context() : base... 并且在我询问(从 Conn 字符串中获取名称)代码的情况下不同的是:public class Context: DbContext { public SchoolDBContext() : base("SchoolDBConnectionString")
    【解决方案2】:

    使连接字符串像

    指向sql客户端

    providerName="System.Data.EntityClient" 
    

    到

    providerName="System.Data.SqlClient"
    

    对于完整的连接字符串,这样做

    <add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
    

    更多连接字符串示例follow the link

    别忘了修改你的 dbcontext

    public class YourContext : DbContext
    {
        public UsersContext()
            : base("BloggingContextCF"){ }
    }
    

    【讨论】:

    • 嗨。我希望从连接字符串中获取名称,但使用我的连接字符串,以及你建议的当在我扩展 DbContext 的类中时,我输入 public BloggingContextCF() : base("BloggingContextCF") { } 我的数据库名称总是像来自 @987654328 的文本@.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2023-03-05
    • 2021-12-30
    • 2013-09-13
    相关资源
    最近更新 更多