Simple.Data

Simple.Data defines a number of commands for the modification of data in a data store. Insert is used to add new data.

Insert

The Insert method allows the insertion of data into your database.

The return value of an Insert method is a single row of data that has just been inserted.

You can insert using two forms, Named parameters and by object. The object can be a POCO or a dynamic (i.e. ExpandoObject).

Note: There are differences in the generated SQL when using Named Parameters or object, where the object includes all properties included on the object, but the Named Parameters only includes those you specify.

Insert (Named Parameters)

var user = _db.Users.Insert(Name: "Steve", Age: 50);            

Generates the following SQL

@p0 = 'Steve'
@p1 = 50
insert into [dbo].[Users] ([Name],[Age]) values (@p0,@p1)

Insert (by object)

var user = new User { Name = "Steve", Age = 50 };
_db.Users.Insert(user);           

Generates the following SQL

@p0 = 'Steve'
@p1 = null
@p2 = 50
insert into [dbo].[Users] ([Name],[Age]) values (@p0,@p1,@p2)

Identity Insert

If your database uses auto-incrementing integer IDs, use the return value of Insert (which is always the single row of data that has just be inserted):

User user1 = new User { Name = "Steve", Age = 50 };
User user2 = _db.Users.Insert(user1);
Debug.Assert(user2.Id != 0); // passes
Debug.Assert(user1.Id != 0); // fails - insert source not given the new ID.

Multi-Insert (by object)

var users = new[]
            {
                new User { Name = "Slartibartfast", Password = "bistromathics", Age = 777 },
                new User { Name = "Wowbagger", Password = "teatime", Age = int.MaxValue }
            };
IList retrows = _db.Users.Insert(users).ToList();      

Generates the following SQL

insert into [dbo].[Users] ([Name],[Password],[Age]) values ('Slartibartfast','bistromathics',777)
insert into [dbo].[Users] ([Name],[Password],[Age]) values ('Wowbagger','teatime',2147483647)