c# - Entity Framework - 冗余连接字符串

标签 c# .net entity-framework configuration ado.net

我在我的项目中使用 Entity Framework 4。框架已经创建了自己的连接字符串,因此我的 web.config connectionStrings 部分文件如下所示:

  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=localhost;user id=user;pwd=pass;initial catalog=VNK" providerName="System.Data.SqlClient" />    
    <add name="VNKEntities" connectionString="metadata=res://*/VNKModel.csdl|res://*/VNKModel.ssdl|res://*/VNKModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=localhost;Initial Catalog=VNK;User ID=user;Password=pass;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

名为 ApplicationServices 的第一个连接字符串是我原来的。第二个名为 VNKEntities 是在生成模型时创建的。

当我检查生成的*.edmx文件时,我发现这个模型正在引用它的连接字符串,如下所示:

    /// <summary>
    /// Initializes a new VNKEntities object using the connection string found in the 'VNKEntities' section of the application configuration file.
    /// </summary>
    public VNKEntities() : base("name=VNKEntities", "VNKEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

我的问题是如何去掉 VNKEntities 连接字符串,只留下 ApplicationServices,我将从我的模型中引用它?我希望只有一个连接字符串到数据库,因为我只使用一个数据库(将构造函数参数从 name=VNKEntities 替换为 name=ApplicationServices 不是工作)。

问候

最佳答案

虽然您可以在代码中创建连接,正如@gandjustas 指出的那样 (+1),但您无法摆脱连接字符串或 EntityConnection

这是因为它实际上并不是多余的。是的,数据库连接部分是多余的,@gandjustas 向您展示了如何删除该冗余。但是, Entity Framework 连接字符串还包含有关您的模型的信息,而您希望保留的连接字符串中的任何地方都找不到这些信息。该模型信息必须来自某个地方。如果您消除 Entity Framework 的连接字符串并在 ObjectContext 上使用参数列表构造函数,您将消除对模型的所有引用。

关于c# - Entity Framework - 冗余连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777722/

相关文章:

c# - ASP MVC 5 路由映射

c# - 如何更改 DateTime 对象在 DataGridView 中的显示方式

asp.net - ObjectDataSource 没有要插入的值

c# - 使用 WPF 和 Entity Framework 将查询绑定(bind)到数据网格

entity-framework - EF6 实体数据模型设计器不适用于目标框架 .net 5.0

c# - GetType().ToString() 返回意外字符

c# - 在 Windows 服务上设置恢复选项

c# - 在 C# 中使用值参数模拟模板

c# - 到 WndProc 的消息是否将值从 32 位操作系统更改为 64 位操作系统?

c# - 是否可以只在 ASP.Net 中处理 404 错误?