由于无参数构造函数,使用 IMultipleResults 从存储过程填充 KeyValuePair 失败

Populating KeyValuePair from stored procedure with IMultipleResults fails due to parameterless constructor

我正在尝试找到一种好方法来获取我在一次数据库旅行中填充下拉列表的所有查找并使用泛型,这样我就不必创建一堆自定义 类。我想避免创建一堆自定义 类,例如 Class IntStringPairClass StringStringPairClass StringIntPair

我知道 C# 有 KeyValuePair 所以我尝试使用它,但它抛出异常:'System.Collections.Generic.KeyValuePair[System.Int32,System.String]' must declare a default (parameterless) constructor in order to be constructed during mapping.'

我看到了这个post:KeyValuePair - no parameterless constructor?

但奇怪的是,如果我只点击一个 table,它会起作用,但如果我从存储过程中使用 IMultipleResults,它就会失败。

所以这有效:

using (MyDataContext db = new MyDataContext(Config.CoreDBConnectionString))
{
    return db.MyTable.Select(p => new KeyValuePair<string, string>(p.Field1, p.Field2)).ToList();
}

但这失败了:

using (MyDataContext db = new MyDataContext(Config.CoreDBConnectionString))
{
    System.Data.Linq.IMultipleResults r = db.GetLookups();
    return r.GetResult<KeyValuePair<int,string>>().ToList();
}

如果我能让最后一个工作,那么我将两全其美,一次数据库旅行和一个通用的解决方案。

我也试过 Dictionary 但我总是 运行 遇到序列化问题。我正在处理的应用程序很旧,所以它使用 Linq to SQL.

而不是 Entity Framework

那么有没有一种方法可以在不创建一堆 类 的情况下做到这一点,最好是 C#/.NET 中内置的使用泛型并允许我一次获得多个结果集的东西?

如果您创建自己的通用对 class,则可以使用它。我用 Value1Value2 属性创建了一个,但如果愿意,您可以创建 Key/Value

public class DBPair<T1, T2> {
    T1 v1;
    T2 v2;

    public DBPair() {
    }

    public DBPair(T1 v1, T2 v2) {
        this.v1 = v1;
        this.v2 = v2;
    }

    public T1 Value1
    {
        get; set;
    }
    public T2 Value2
    {
        get; set;
    }
}

注意:如果您需要 KeyValuePair 的某些其他功能,例如成员平等测试或哈希码生成,您将需要添加这些方法,或将结果传输到新的 KeyValuePair检索后

然后就可以这样使用了:

using (MyDataContext db = new MyDataContext(Config.CoreDBConnectionString))        
    return db.GetLookups().GetResult<DBPair<int,string>>().ToList();