使用 linq2db 执行原始 SQL 字符串

ric*_*fox 6 c# linq2db

使用 linq2db ( https://github.com/linq2db/linq2db ) 我可以执行原始 SQL 字符串并将结果作为dynamic?

我正在寻找类似 ADO.NETDBCommand.ExecuteReader或 Dapper 的Query<dynamic>.

BAn*_*rei 7

首先,您需要创建一个具有与查询结果一样多的属性的类。

第二件重要的事情是,您需要为此类的每个属性添加属性,以匹配执行此“选择”后产生的列的名称。例如:[Column(@"user_firstname")]

之后,您可以将此类放在查询的调用中。我可以证明:

using (var db = new TestDB())
{
   var usersList = db.Query<YourCustomClass>("your select query here").ToList();
}
Run Code Online (Sandbox Code Playgroud)

现在,您将拥有“YourCustomClass”类型列表中的所有数据。

我希望这是您正在寻找的答案。


Ser*_*eyA 5

linq2db 是强类型的,但您可以执行原始 sql 并将结果映射到匿名类。例如:

var result = ExecuteAnonymous(db, 
    "select id, name from sysobjects", 
    new { id = 0, name = "" });
Run Code Online (Sandbox Code Playgroud)

其中 ExecuteAnonumous 是辅助方法:

IQueryable<T> ExecuteAnonymous(DataConnection db, string sql, T typeObject)
{
    return db.Query<T>(sql);
}
Run Code Online (Sandbox Code Playgroud)

  • linq2db 具有像 ExecuteAnonymous 一样的“查询”重载(静态 IEnumerable&lt;T&gt; Query&lt;T&gt;(此 DataConnection 连接、T 模板、字符串 sql、params DataParameter[] 参数)) (5认同)

Евг*_*вин 5

您可以轻松地自己实现:

            foreach (var rec in DataConnection.Query<dynamic>(reader =>
            {
                IDictionary<string, object> eo = new ExpandoObject();
                for (var index = 0; index < reader.FieldCount; index++)
                {
                    eo.Add(reader.GetName(index), reader.GetValue(index));
                }
                return eo;
            }, "select first 2 \"Guid\", \"DongleID\" from \"Sellings\""))
            {
                Console.WriteLine(rec.DongleID);
            }
Run Code Online (Sandbox Code Playgroud)