Skip to content
sdrapkin edited this page Feb 9, 2017 · 5 revisions

Signature:

QueryInfo QB.Insert<T>(
	T obj,
	Predicate<string> propFilter = null,
	string tableName = null
)

Assume we have the following class:

// contains "SequentialGuid" and quiery builder "QB"
using SecurityDriven.TinyORM.Helpers; 

public class Person
{
	public string Name { get; set; } = "[Default]";
	public Guid Id { get; set; } = SequentialGuid.NewSequentialGuid();
	public DateTime BirthDate { get; set;} = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
}

Let's generate SQL to insert an instance of Person:

var p = new Person();
p.Dump(); // shows nicely in LinqPad - comment out otherwise
// [Person]
//  Name      : "[Default]"
//  Id        :  eb9d3e5d-2ba8-a0c7-e93b-11e6e7357a6d
//  BirthDate :  1753-01-01 00:00:00

var query = QB.Insert(p);
query.Dump(); // shows nicely in LinqPad - comment out otherwise
// [QueryInfo]
// [SQL] : "INSERT [Person] ([Name],[Id],[BirthDate]) VALUES (@@Name,@@Id,@@BirthDate)"
// [ParameterMap] : [Key : Value]
//   "@@Name"      : "[Default]"
//   "@@Id"        : eb9d3e5d-2ba8-a0c7-e93b-11e6e7357a6d
//   "@@BirthDate" : 1753-01-01 00:00:00

await db.QueryAsync(query); // executing the built query

Showing parameterization and a custom table name:

var query = QB.Insert(obj: new { Name = "Stan", Id = 123}, tableName: "CustomTableName".AsSqlName());
query.Dump(); // shows nicely in LinqPad - comment out otherwise
// [QueryInfo]
// [SQL] : "INSERT [CustomTableName] ([Name],[Id]) VALUES (@@Name,@@Id)"
// [ParameterMap] : [ Key : Value]
//   "@@Name" : "Stan"
//   "@@Id"   : 123

What if Id is an auto-incrementing IDENTITY column, which needs to be excluded from INSERT and its db-generated value retrieved:

var query = QB.Insert(
	obj: new { Name = "Stan", Id = 123},
	tableName: "CustomTableName".AsSqlName(),
	propFilter: n => !(n == "Id") );
query.Dump(); // shows nicely in LinqPad - comment out otherwise
// [QueryInfo]
// [SQL] : "INSERT [CustomTableName] ([Name]) VALUES (@@Name)"
// [ParameterMap] : [ Key : Value]
//   "@@Name" : "Stan"

int id = (await db.QueryAsync(query.SQL + "; SELECT SCOPE_IDENTITY();", query.ParameterMap))[0];

Clone this wiki locally