Executing raw SQL string using linq2db

白昼怎懂夜的黑 提交于 2019-12-10 09:38:00

问题


Using linq2db (https://github.com/linq2db/linq2db) can I execute a raw SQL string and get the result as a dynamic?

I'm looking for something like ADO.NET's DBCommand.ExecuteReader or Dapper's Query<dynamic>.


回答1:


You can easy implements it yourself:

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



回答2:


First, you need to create a class that has so many properties as your query result.

Second important thing is that you need to add attributes to each property of this class to match the name of column that results after executing this "select". For example: [Column(@"user_firstname")].

After that you can put this class in the call of the query. I can demonstrate it:

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

Now you will have all data in your list of type "YourCustomClass".

I hope this is the answer that you were looking for.




回答3:


linq2db is strongly typed but you can execute raw sql and map the result to anonymous class. For example:

var result = ExecuteAnonymous(db, 
    "select id, name from sysobjects", 
    new { id = 0, name = "" });

Where ExecuteAnonumous is helper method:

IQueryable<T> ExecuteAnonymous(DataConnection db, string sql, T typeObject)
{
    return db.Query<T>(sql);
}


来源:https://stackoverflow.com/questions/48157120/executing-raw-sql-string-using-linq2db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!