简体   繁体   English

如何使用dapper.net在参数内传递对象的整个属性

[英]How to pass whole properties of an object inside params using dapper.net

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 我刚刚开始在我的项目中使用Dapper,但我找不到在Dapper.Net中将对象作为参数传递的方法。

Is there any way of any process to pass object as parameter then Dapper will map the object properties to the parameterized SQL? 是否有任何方法将对象作为参数传递,然后Dapper会将对象属性映射到参数化的SQL?

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?
    }

}

I dont think that you can do that only dapper but with the Dapper.Contrib. 我不认为您只能使用Dapper.Contrib来完成该操作。 Dapper.Contrib contains usefull extentions like 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>();

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 在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; }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM