I have sql table tbl_persons with fields: first_name, last_name, first_name_eng, last_name_eng.
And a Model:
public class PersonName
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Person
{
public PersonName Name { get;set; }
public PersonName NameEng { get;set; }
}
How can I map rows from tbl_persons to Person objects?
You can use the Multi-Mapping API of Dapper
This should work fine.
var result = new List<Person>();
var q = "SELECT null as S, first_name as FirstName,
last_name AS LastName,first_name_eng AS FirstName,
last_name_eng AS LastName FROM tbl_persons";
using (var con = new SqlConnection("YourConnStringHere")
{
result = con.Query<Person, PersonName,PersonName, Person>(q, (p,n,ne) =>
{ p.Name = n; p.NameEng =ne; return p; },
splitOn: "FirstName,FirstName").ToList();
}
Note : You need the null as S
as a dummy column even though you are not using it in your class. If you do not provide that, you will get an error with your current class structure (no non-complex type properties)