Insert with Dapper Micro ORM and ASP.NET MVC 3

As I have already posted about the how to fetch data in my earlier post for Dapper ORM. In this post I am going to explain how we can insert data with the dapper ORM. So let’s extend the earlier post project. As explained in earlier post I have already created a class called CustomerDB this class will contains all the operation with Dapper Micro ORM. So For inserting data let’s first create CREATE method like following in CutomerDB Class like following. In that I have create a simple Insert Query in string and then using connection.execute method to execute method. Following is code for that.

public class CustomerDB
{
    public string Connectionstring = @"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

    public IEnumerable<Customer> GetCustomers()
    {
        using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
        {
            sqlConnection.Open();
            var customer = sqlConnection.Query<Customer>("Select * from Customer");
            return customer;

        }
    }

    
    public string  Create(Customer customerEntity)
    {
        try
        {
            using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
            {
                sqlConnection.Open();
               
                string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
                sqlConnection.Execute(sqlQuery,
                                      new
                                          {
                                              customerEntity.FirstName,
                                              customerEntity.LastName,
                                              customerEntity.Address,
                                              customerEntity.City
                                          });

                
                sqlConnection.Close();

            }
            return "Created";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }

    }

}

Now we are ready with Create Method for database now let’s create two ActionResult for the Creating customer like following in Customer Controller like following.

public ActionResult Create()
{
    return View();
}

//
// POST: /Customer/Create

[HttpPost]
public ActionResult Create(Customer customer)
{
    try
    {
        // TODO: Add insert logic here
        var customerEntities = new CustomerDB();
        customerEntities.Create(customer);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

Now we are ready with the both ActionResult. First ActionResult will return simple view of Create which we are going to create now and another ActionResult Create will get customer object from the form submitted and will call our create method of CustomerDB Class. Now it’s time to create a view for adding customer. Right Click return view Statement in Create Action Result and Click Add View and Just Create view like following.

CreateView

That’s it now we are ready. Now let’s test it in browser. Like following.

AddNew

Now let’s click and create and then it will redirect us to customer list page like following. Where you can see the newly added details.

View

So that’s it. Its very easy to Insert data with Dapper Micro ORM. Hope you like it…Stat tuned for more.

Note:  For reference of this post you can also see my first post called -Playing with dapper Micro ORM and ASP.NET MVC 3.0.

Shout it
Published Thursday, May 19, 2011 5:26 PM by Jalpesh P. Vadgama

Comments

# re: Insert with Dapper Micro ORM and ASP.NET MVC 3

Thursday, May 19, 2011 7:08 PM by Sam Saffron

Please please please ... do not use string.Format to pass in params, we support multiple "approved" ways of passing in params like

Execute<User>("insert table(col,col2) values (@col, @col2)", new {col, col2});

see: stackoverflow.com/.../performing-inserts-and-updates-with-dapper

# re: Insert with Dapper Micro ORM and ASP.NET MVC 3

Thursday, May 19, 2011 9:54 PM by James Harris

Please don't post examples of string concat to build sql commands. It's the primary reason that PHP code is so typically full of security issues (all the bad examples/tutorials on the net).

Always use parameterised queries, never use String.Format or similar.

If I specify say my city as '); DELETE * FROM CUSTOMER what would happen? Even apart from security, if someone has an apostrophe in their name O'Connor or similar, it will give an sql error.

# Edit/Update with dapper ORM and ASP.NET MVC 3

Friday, May 20, 2011 9:20 PM by Edit/Update with dapper ORM and ASP.NET MVC 3

Pingback from  Edit/Update with dapper ORM and ASP.NET MVC 3

# Edit/Update with dapper ORM and ASP.NET MVC 3

Saturday, May 21, 2011 5:10 AM by DotNetJalps

In last two post I have already written about Getting data and adding data with Dapper Micro ORM. In

# re: Insert with Dapper Micro ORM and ASP.NET MVC 3

Saturday, May 21, 2011 5:14 AM by Jalpesh P. Vadgama

@Sam,@James- I have Corrected it. Thanks for sharing info.

# Delete with Dapper ORM and ASP.NET MVC 3

Saturday, May 21, 2011 6:49 AM by DotNetJalps

I have been writing few posts about Dapper ORM and ASP.NET MVC3 for data manipulation. In this post I

# re: Insert with Dapper Micro ORM and ASP.NET MVC 3

Wednesday, May 09, 2012 8:35 AM by Casimira

Greetings! Very helpful advice in this particular

article! It's the little changes which will make the largest changes. Thanks a lot for sharing!