1
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: mapping

Source Error: 


Line 45:     #endregion
Line 46:        
Line 47:        public db() : 
Line 48:                base(global::data.Properties.Settings.Default.nanocrmConnectionString, mappingSource)
Line 49:        {

如果我实现这样的类,这就是我得到的:

partial class db
{
    static db _db = new db();

    public static db GetInstance()
    {
        return _db;
    }
}

db 是一个 linq2sql 数据上下文

为什么会发生这种情况以及如何解决这个问题?

UPD:该文件由 linq2sql 生成:

    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

    public db() : 
            base(global::data.Properties.Settings.Default.nanocrmConnectionString, mappingSource)
    {
        OnCreated();
    }

如果我在方法内实例化 db(不是这里的属性)一切正常。并且静态方法一直工作到今天早上,但现在即使是 2 天前的版本(从存储库恢复)也出现了同样的错误。

更新 2

所以这是我解决问题后的部分课程:

namespace data
{
using System.Data.Linq.Mapping;

partial class db
{
    static db _db = new db(global::data.Properties.Settings.Default.nanocrmConnectionString, new AttributeMappingSource());

    public static db GetInstance()
    {
        return _db;
    }
}
}
4

1 回答 1

0

啊,我刚看了一下。似乎由于某种原因未初始化静态变量。

现在,您可以通过执行以下操作来解决问题:

static db _db = new db(
 global::data.Properties.Settings.Default.nanocrmConnectionString, 
 new AttributeMappingSource());

虽然这mappingSource仍然是空的,但这很奇怪。

现在想想,这可能是部分类是如何拼接在一起的。出于某种原因,它使用您的代码作为整个类的“前缀”。正如我所料,它似乎在mappingSource初始化时_db没有被初始化。

进一步解释导致问题的原因。

静态成员的初始化顺序是未定义的,但通常它们往往是有序的。

以下面的程序为例,使事情进一步复杂化。

主文件

  class Printer
  {
    public Printer(string s)
    {
      Console.WriteLine(s);
    }
  }

  partial class Program
  {
    static void Main()
    {
      new Program();
      Console.ReadLine();
    }
  }

X.cs

  partial class Program
  {
    static Printer x = new Printer("x");
  }

Y.cs

  partial class Program
  {
    static Printer y = new Printer("y");
  }

Z.cs

  partial class Program
  {
    static Printer z = new Printer("z");
  }

现在取决于如何为编译器提供类,初始化的顺序可以改变。

尝试:

  • csc Main.cs X.cs Y.cs Z.cs
  • csc Main.cs Y.cs Z.cs X.cs
  • csc Main.cs Y.cs X.cs Z.cs

我怀疑你每次都会看到不同的结果。

于 2010-04-14T05:01:19.857 回答