我刚开始将Dapper用于我的项目和 我无法找到一种方法将对象作为参数传递给Dapper.Net
是否有任何方法将对象作为参数传递,然后Dapper会将对象属性映射到参数化的S.Q.L?
而不是使用它:
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?
}
}
答案 0 :(得分:1)
我不认为你只能使用Dapper.Contrib来做到这一点。 Dapper.Contrib包含有用的扩展,如
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>();
有关详细信息,请查看here
在Dapper.contrib的帮助下,你可以做到这样的事情,甚至不用写sql查询并传递参数
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; }
}