Executing raw SQL string using linq2db

三世轮回 提交于 2019-12-05 11:57:51

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

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.

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