Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing raw SQL string using linq2db

Tags:

c#

linq2db

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>.

like image 276
rickythefox Avatar asked Jan 08 '18 19:01

rickythefox


Video Answer


2 Answers

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.

like image 130
BAndrei Avatar answered Sep 20 '22 06:09

BAndrei


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);
            }
like image 37
Евгений Савин Avatar answered Sep 20 '22 06:09

Евгений Савин