Reputation: 77
I am just starting to use Dapper for my projects and I just cant find a way to pass an object as a parameter in Dapper.Net
Is there any way of any process to pass object as parameter then Dapper will map the object properties to the parameterized S.Q.L?
instead of using this:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
static void Main(string[] args)
{
Product product = new Product()
{
Name = "DHS - 3 Star Ball",
Price = 11,
Category = "Table Tennis",
Description = "ITTF - Approved Table Tennis Ball",
ProductID = 1
};
using(IDbConnection dbConnection = ...ConnectionStrings)
{
string query = "INSERT INTO Products (Properties here) VALUES (@Properties)";
dbConnection.Execute(query, ...product.properties here sample: product.ProductID); //<------- Is there any substitute to this?
}
}
Upvotes: 1
Views: 2001
Reputation: 3502
I dont think that you can do that only dapper but with the Dapper.Contrib. Dapper.Contrib contains usefull extentions like
T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();
for more information you can take a look at here
With the help of Dapper.contrib ,you can do that something like this without even write sql query and pass the parameters
class Program
{
static void Main(string[] args)
{
var usr = new User()
{
Email = "testmail",
Name = "testname"
};
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString;
using (IDbConnection dbConnection = new SqlConnection(connection))
{
dbConnection.Open();
long insert = dbConnection.Insert<User>(usr);
}
}
}
[Table("[User]")]
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Upvotes: 2