Linq2DB 和动态查询

Linq2DB and query for dynamic

我试图在没有创建映射模型的情况下执行查询。 考虑这个片段

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' 的定义'

遇到这种情况怎么办? 谢谢

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

作为解决方法,我建议定义额外的 class 来读取这样的结果:

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;
    }
}