Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper's parameterized Update and Insert?

Tags:

c#

sql

dapper

I am using Dapper for my windows C# forms application. I noticed that most of their CRUD operations take class name as parameter. For example two tables as below :

    "Employee" Table
        Column Name  | Data Type |
        -------------------------
        EmpName      | string    |
        EmpNo        | string    |
        --------------------------

Employee.cs
[Table("Employee")]
public class Employee
{
   [Key]
   public string EmpNo {get;set;}
   public string EmpName {get;set;}
}

    "User" Table
        Column Name   | Data Type |
        -------------------------
        UserName      | string    |
        UserNo        | string    |
        --------------------------
User.cs
[Table("User")]
public class User
{
   [Key]
   public string UserNo {get;set;}
   public string UserName {get;set;}
}


    eg. var users= connection.Query<User>("select * from User" );
        var employees = connnection.GetList<Employee>();

will do the appropriate tasks. but, as per my knowledge connection.Insert<User>(user); or connection.Update<Employee>(emp); does not exist. Please correct me if I am wrong, is there any work around to have Update and Insert with letting dapper know the class type ? I am well aware about Query() and Execute(), in fact I am using those right now. Is there anyway possible to make it as easy as GetList(ClassName); is ?

like image 941
Рахул Маквана Avatar asked Jun 23 '16 19:06

Рахул Маквана


1 Answers

Dapper handles things a bit differently than what you are asking for. There is no Insert or Update method. Instead you will want to do it like this for Insert:

var p = new Product { Name = "Sam", Description = "Developer" };
p.Id = cnn.Query<int>(@"insert Products(Name,Description) 
values (@Name,@Description) 
select cast(scope_identity() as int)", p).First();

This is directly from Sam Saffron, https://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper.

For Updates, you will want code like this:

public bool Update(Employee employee)
{
    string query = "UPDATE EMPLOYEE SET NAME = @Name WHERE Id = @Id";
    var count = this.db.Execute(query, employee);
    return count > 0;
}
like image 65
Ben Hoffman Avatar answered Sep 30 '22 15:09

Ben Hoffman