Linq2DB和动态查询

时间:2019-02-05 08:23:00

标签: linq2db

我正在尝试执行查询,而没有创建一个映射它的模型。 考虑这个片段

public IDictionary<string, int> GetParentelaMapping()
    {
        using (var conn = dataContextFactory.Create())
        {
            var result = conn.Query<dynamic>("SELECT ID_GRADO_PARENTELA,GRADO_PARENTELA FROM GRADO_PARENTELA")
                .ToDictionary(
                    row => (string)row.GRADO_PARENTELA,
                    row => (int)row.ID_GRADO_PARENTELA, StringComparer.OrdinalIgnoreCase);

            return result;
        }
    }

它给了我一个例外 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“ int”不包含“ GRADO_PARENTELA”的定义

如何处理这种情况? 谢谢

1 个答案:

答案 0 :(得分:2)

很遗憾,当前不支持此功能。为此,请跟踪新的issue #1591

作为一种解决方法,我建议定义其他类以读取此类结果:

class ParentelaMapping
{
    public int ID_GRADO_PARENTELA { get; set; }
    pulbic string GRADO_PARENTELA { get; set; }
}

public IDictionary<string, int> GetParentelaMapping()
{
    using (var conn = dataContextFactory.Create())
    {
        var result = conn.Query<ParentelaMapping>("SELECT ID_GRADO_PARENTELA,GRADO_PARENTELA FROM GRADO_PARENTELA")
            .ToDictionary(
                row => row.GRADO_PARENTELA,
                row => row.ID_GRADO_PARENTELA, StringComparer.OrdinalIgnoreCase);

        return result;
    }
}

P.S。

linq2db 旨在更好地与linq查询配合使用,因此请考虑通过以下方式重写查询:

[Table("GRADO_PARENTELA")]
class GrandoParentela
{
    public int ID_GRADO_PARENTELA { get; set; }
    pulbic string GRADO_PARENTELA { get; set; }
}

public IDictionary<string, int> GetParentelaMapping()
{
    using (var conn = dataContextFactory.Create())
    {
        var result = conn.GetTable<GrandoParentela>()
            .ToDictionary(
                row => row.GRADO_PARENTELA,
                row => row.ID_GRADO_PARENTELA, StringComparer.OrdinalIgnoreCase);

        return result;
    }
}