c# - 如何在代码中添加 Entity Framework 6 提供程序?

标签 c# connection-string entity-framework-6

我在 C# 应用程序中使用 Entity Framework 6,它运行良好。创建模型时,会生成包含所有必要配置的 app.config。现在我不喜欢在 app.config 中有东西,所以我使用连接字符串生成器。我成功地从 app.config 文件中删除了除此之外的所有内容:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

如果我删除它,它将不起作用。那么如何将该配置转换为 C# 代码呢? 我该怎么做?我查看了基于代码的配置 ( http://msdn.microsoft.com/en-us/data/jj680699 ),但它没有帮助。

创建连接字符串的部分类如下所示:

public partial class LogEntities
    {
        public LogEntities(string serverName)
            : base(GetConnectionString(serverName))
        {
        }

        public static string GetConnectionString(string serverName)
        {
            // Specify the provider name, server and database.
            const string databaseName = "_LOG";

            // Initialize the connection string builder for the underlying provider.
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
            {
                DataSource = serverName,
                InitialCatalog = databaseName,
                IntegratedSecurity = true,
                MultipleActiveResultSets = true
            };

            // Initialize the EntityConnectionStringBuilder.
            System.Data.EntityClient.EntityConnectionStringBuilder entityBuilder = new System.Data.EntityClient.EntityConnectionStringBuilder();
            entityBuilder.Provider = "System.Data.SqlClient";

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/myproject.LogModel.csdl|res://*/myproject.LogModel.ssdl|res://*/myproject.LogModel.msl";

            return entityBuilder.ConnectionString;
        }
    }

在此先感谢您的帮助。

最佳答案

在 EF6 中,您可以使用代码库配置。看看this文章了解更多详情。它展示了如何设置默认连接工厂(使用 SetDefaultConnectionFactory 方法)。要设置提供程序,您可以使用 SetProviderServices 方法。

关于c# - 如何在代码中添加 Entity Framework 6 提供程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808549/

相关文章:

entity-framework - .net 核心未连接到 appsettings.json connectionstrings 中的已更改数据库

c# - 尽管从 Azure 复制了连接字符串,但仍无法授权

entity-framework - 如何通过 LINQ Include 在一个查询中检索子数据以提高性能?

c# - Interop Excel UsedRange 行计数不正确

c# - 我需要取消订阅动态菜单项事件吗?

c# - 匿名类型对象或动态

sql-server-2008 - 为什么 EntityConnection 对象不包含登录密码?

c# - EF6 DbSet<T> 在 Moq 中返回 null

c# - 禁用 Entity Framework 日期时间默认值

c# - 使用 Reactive Extensions (RX),是否可以添加 "Pause"命令?