SecurityDriven.TinyORM icon indicating copy to clipboard operation
SecurityDriven.TinyORM copied to clipboard

How to do field mapping via a POCO factory

Open dsmeltz opened this issue 4 years ago • 2 comments

I'm trying to figure out how to map columns from a query to their appropriate properties, via the poco factory feature. I don't know what is being passed to the factory, if anything.

var gms = rows.ToObjectArray(() => new GeneralManager( what_goes_here ));

Is what I'm attempting doable?

dsmeltz avatar May 25 '21 13:05 dsmeltz

Hi @dsmeltz, does this example help? [Linqpad]

async Task Main()
{
	string connString = "Server=.\\SQL2019;Database=TempDB;Trusted_Connection=True;";
	var db = DbContext.Create(connString);

	var rows = await db.QueryAsync("SELECT * FROM SYS.OBJECTS;");

	var pocoArray = rows.ToObjectArray<POCO>(); // add "using SecurityDriven.TinyORM.Extensions;"
	var pocoArray_via_factory = rows.ToObjectArray(() => new POCO());

	pocoArray.Dump();
}

public class POCO
{
	public string name { get; set; }
	public int object_id { get; set; }
	public int schema_id { get; set; }
	public int parent_object_id { get; set; }
	public string type { get; set; }
	public string type_desc { get; set; }
	public DateTime create_date { get; set; }
	public DateTime modify_date { get; set; }
	public bool is_ms_shipped { get; set; }
}

The POCO property names must match the returned column-names to be automatically mapped (case-sensitive). There is also .ToMappedObjectArray() extension, in case you need to provide a custom RowStore-to-T mapper.

sdrapkin avatar May 26 '21 01:05 sdrapkin

Perfect! Here's an example for others looking to do the same:

r is a RowStore. So now you can do row things with it, like mapping the SQL output columns to your class.

var gms = rows.ToMappedObjectArray<GeneralManager>(r => 
    new GeneralManager { 
        ContactId = (int) r["ContactID"],
        FullName = r["GM"].ToString()
});

public class GeneralManager
{
	public string FullName { get; set; }
	public int ContactId { get; set; }
}

dsmeltz avatar May 26 '21 12:05 dsmeltz