Reputation: 954
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 ?
Upvotes: 5
Views: 18885
Reputation: 954
Thanks to Marc Gravell. I found it here.
Dapper's open source development do have implementation for Insert<ClassName>(obj)
and Update<ClassName>(obj)
.
Upvotes: 3
Reputation: 8259
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;
}
Upvotes: 4