here is the code
var customers = db.ExecuteQuery<Customer>(@"SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City, Region, PostalCode, Country, Phone, Fax
FROM dbo.Customers
WHERE City = {0}", "London");
foreach (Customer c in customers)
Console.WriteLine(c.ContactName);
code execute sql and retun a customer record. my question how result can be stored in customer class automatically….which i do not understand. if u see this line of code
db.ExecuteQuery<Customer> from here we can understand that customer result will be return and customer data will be stored in customer class. how automatically data can be stored & assign to right property in customer class because a customer class CustomerID property name could be CustID….then what will happen.
the line db.ExecuteQuery<Customer> is very confusing for me and i just do not understand a new customer instance will be created with return customer data….so plzz discuss in detail.
ExecuteQueryjust runs arbitrary SQL (after applyingstring.Format-esque parameterization) and then materializes theIDataReaderresults as a sequence of objects.Note that the mappings between mapped types and the db-columns/type-members is well defined by the data-context (usually via attributes on the members, but not always), but IIRC
ExecuteQuerydoes not apply these mapping (I’m happy to be corrected here). You can inspect this viadb.Mapping.GetMetaType(typeof(Customer)).The fundamentals here are no different to if you executed
except the
db.Customersversion can apply more mappings etc.The materialization itself (i.e. creating the object and setting members) is an example of reflection and meta-programming; most ORMs and micro-ORMs will work pretty much the same there: inspect the type (
Customerabove) and inspect the fields in the reader – and then build some code on-the-fly (usually cached) that will create the new objects and set the members.