I am currently mapping the database query output to a class object in the following. Is there anyway I can directly map it with out using foreach loop?
public class Person { public int Id { get; set; } public string Name { get; set; } public int Address { get; set; } } string select = "SELECT Id, Name, Address FROM emp where Id = 100"; string dbConnection="Server = TestServer; userid = XXXX; password = YYYYY; database = TestDB; port = 1234"; Person person = new Person(); using (var connection = new MySqlConnection(dbConnection)) { var v = await connection.QueryAsync<Person>(select); if (v != null) { foreach (var res in v) { person.Id = res.Id; person.Name = res.Name; person.Address = res.Address; } } }
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The code doesn’t make logical sense as you are looping over a list of people & overwriting a single Person
object with every new person being enumerated.
That aside, the result of await connection.QueryAsync<Person>(select);
will be of type IEnumerable<Person>
.
var v = await connection.QueryAsync<Person>(select);
is equal to:
IEnumerable<Person> = await connection.QueryAsync<Person>(select);
You already have a collection of Person
objects mapped.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0