C#,无法理解这个错误?

时间:2010-04-30 17:15:21

标签: c# .net

我正在使用VS2008。我有一个项目SystemSoftware项目,与数据库连接,我们正在使用L2E。我有一个RuntimeInfo类,其中包含一些共享信息。它看起来像这样:

public class RuntimeInfo
    {
        public const int PWD_ExpireDays = 30;

        private static RuntimeInfo thisObj = new RuntimeInfo();

        public static string AndeDBConnStr = ConfigurationManager.ConnectionStrings["AndeDBEntities"].ConnectionString;

        private RuntimeInfo() {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>Return this singleton object</returns>
        public static RuntimeInfo getRuntimeInfo()
        {
            return thisObj;
        }
}

现在我在解决方案中添加了一个帮助项目AndeDataViewer,该项目创建了一个简单的UI来显示数据库中的数据以进行测试/验证。

我不想在帮助项目中创建另一组Entity Data Model。我刚刚将所有相关文件添加为新助手项目中的链接。

AndeDataViewer项目中,我从connection stringRuntimeInfo获取SystemSoftware,这是我AndeDataViewer项目中的一个类作为链接文件。 public class DbAccess : IDisposable { private String connStr = String.Empty; public DbAccess() { connStr = RuntimeInfo.AndeDBConnStr; } } 中的代码是这样的:

SystemSoftware

我的RuntimeInfo工作正常,这意味着AndeDataViewer类在那里没有问题。但是当我运行我的connStr = RuntimeInfo.AndeDBConnStr; 时,上面的构造函数中的语句

System.TypeInitializationException was unhandled
  Message="The type initializer for 'MyCompany.SystemSoftware.SystemInfo.RuntimeInfo' threw an exception."
  Source="AndeDataViewer"
  TypeName="MyCompany.SystemSoftware.SystemInfo.RuntimeInfo"
  StackTrace:
       at AndeDataViewer.DbAccess..ctor() in C:\workspace\SystemSoftware\Other\AndeDataViewer\AndeDataViewer\DbAccess.cs:line 17
       at AndeDataViewer.Window1.rbRawData_Checked(Object sender, RoutedEventArgs e) in C:\workspace\SystemSoftware\Other\AndeDataViewer\AndeDataViewer\Window1.xaml.cs:line 69
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
      ....
InnerException: System.NullReferenceException
       Message="Object reference not set to an instance of an object."
       Source="AndeDataViewer"
       StackTrace:
            at MyCompany.SystemSoftware.SystemInfo.RuntimeInfo..cctor() in C:\workspace\SystemSoftware\SystemSoftware\src\systeminfo\RuntimeInfo.cs:line 24
       InnerException: 

,抛出异常。异常复制在此处:

EDIT:

我无法理解这一点,因为它对我来说很好但是为什么有例外?当类是链接类时,我们无法访问静态变量?链接的类应该与我认为的本地类相同。 “链接”在这里意味着当我添加文件时,我使用“添加为链接”。

如何避免此异常?

{{1}}

我将SystemSoftware的App.config添加到AndeDataViewer作为链接。然后解决了这个问题,但我不喜欢它。如果我已经在那里有App.config怎么样?我不想手动复制连接字符串,因为“手动”意味着没有好处。

对于那些有多个项目共享一个数据库的人,当您遇到问题时,这个链接可能会很有帮助:MetadataException: Unable to load the specified metadata resource

3 个答案:

答案 0 :(得分:3)

如果你的应用程序.config文件没有定义连接字符串名称“AndeDBEntities”,你会看到这个。

该行

    public static string AndeDBConnStr = 
       ConfigurationManager.ConnectionStrings["AndeDBEntities"].ConnectionString;

访问可能不存在的ConnectionString返回的对象的ConnectionStrings["AndeDBEntities"]属性。

答案 1 :(得分:0)

你的静态构造函数中有异常。明确地创建它并移动所有静态初始化器。然后调试:)

答案 2 :(得分:0)

AndeDataViewer项目没有配置条目。假设这是一个Winforms应用程序,您需要在该项目中定义一个app.config。