【问题标题】:New Instance of object skipping overloaded constructor对象跳过重载构造函数的新实例
【发布时间】:2013-07-12 13:53:27
【问题描述】:

使用 vs2012,我有一个包含 .edmx 文件和 linq 的测试单元项目(用于测试服务)。 edmx 是在设计时创建的,我创建了一个对象(称为 Store.Data.Common),它从 App.Config 文件中检索连接字符串(解密字符串并构建包括元数据在内的整个字符串):

//Object is called Store.Data.Common
public static string GetConnectionString(string databaseName)
{
    var security = new Security();

    var connectionString = security.GetDecoded(ConfigurationManager.ConnectionStrings[databaseName+"Encrypted"].ToString(), 0);
    var environment = ConfigurationManager.AppSettings["Environment"].ToString();
    var dataSource = security.GetDecoded(ConfigurationManager.AppSettings[environment], 0);

    connectionString = string.Format(connectionString, dataSource);

    return connectionString;
}

我还修改了 .tt 文件以包含构造函数的重载以调用此方法来构建连接字符串,如下所示:

//Original Constructor which I modified and added the parameter to pass to the other constructor.
public StoreContext()
 : base("name=StoreContext")
{
}

//Constructor I added:
public StoreContext(string connection)
{
    Store.Data.Common.ConnectionBuilder.GetConnectionString("StoreContext");
}

一切都正确构建,但是,当我尝试为 StoreContext 新建一个对象并将构造函数留空时,它永远不会到达第二个构造函数:

StoreContext storeContext = new StoreContext();

当我调试这个测试并遍历它时,它只会到达第一个构造函数,仅此而已。显然,如果我这样做:

StoreContext storeContext = new StoreContext("Blah");

然后它按预期进入第二个....我的问题是,为什么第一个方法在没有传递给构造函数时不起作用?从技术上讲,它应该可以工作,对吧?

【问题讨论】:

    标签: c# visual-studio-2010 edmx


    【解决方案1】:

    我认为你的意思是使用

    public StoreContext()
      : this("name=StoreContext")
    {
    }
    

    (使用this 而不是base)。

    使用this() 意味着您正在调用同一个类的构造函数。当您说base() 时,您是在尝试调用基类的构造函数。

    编辑:看起来您也没有使用传递给该非默认构造函数的参数。但这是另一个问题,不是问题的根源。

    【讨论】:

    • 我的平板电脑太快了! :)
    • @Tim 使这些更改有效,但是当我尝试查询数据时,我收到错误“使用 T4 模板生成的数据库优先和模型优先开发的代码如果在代码中使用可能无法正常工作第一种模式。要继续使用数据库优先或模型优先,请确保在执行应用程序的配置文件中指定实体框架连接字符串。要使用从 Database First 或 Model First 生成的这些类,使用 Code First 添加使用属性或 DbModelBuilder API 的任何其他配置,然后删除引发此异常的代码。'
    • 我不太熟悉 T4 模板和 Db First/Model First/Code first 配置。如果您不确定,您可能想针对该新错误提出一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 2015-12-04
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2015-01-24
    相关资源
    最近更新 更多