Skip to content

Values Object Creator

Ophir Oren edited this page Oct 22, 2016 · 2 revisions

A common task with Micro-ORMs is passing an anonymous object with the values needed for executing the SQL statement. To save the time and lines of code in writing these objects, Poco.Sql.NetCore has an helper class that knows how to create an object that's combined of your domain objects, and is specific to SQL statement.

A normal execution of an SQL statement might look something like this:

var user = connection.Query<User>("select * from Users where UserId = @UserId", new {
    UserId = 100
});

Or

connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)", new { a = 1, b = 1 });

So to save us from writing and assigning all the properties we need to pass, we would use the ValuesObject class and call the static Create method.

Examples

Create a value object from one object with all it's parameters:

var data = ValuesObject.Create(myObject);

Create a value object combined with more than one object:

var data = ValuesObject.Create(myFirstObject, mySecondObject, myThirdObject /* ... */);

Notice that if the same property name exists in more than one object - the property from the first object passed in the parenthesis will be used.

Create values object with parameters specific to our SQL statement

var sql = "insert into Users(FirstName, LastName, DateOfBirth, LuckyNumber, IsRegistered) values(@FirstName, @LastName, @DateOfBirth, @LuckyNumber, @IsRegistered)";
var data = ValuesObject.Create(sql, myUserObject);

If the first param that is passed to the Create method is a string, it will take only the properties from the passed objects that appears in the SQL statement that was passed.

Notice: parameter names in the SQL statement must match the properties in the objects

Clone this wiki locally