asp.net - Dapper 问题。从返回的对象中获取值

标签 asp.net object dapper

刚刚开始学习Dapper。我有 ADO.NET 背景。使用我下载的演示,我可以将网络表单中的数据插入/删除到 MySql 表中。然而,我已经搜索了整个上午了。

在通过 ID 从数据库中检索单行时,它不会返回 LIST<>,它似乎只是一个对象(使用我下载的演示中的代码)。查询有效,我取回了对象。它具有以下字段:“ProductID、描述和价格”。

我获取这三个字段的值的唯一方法是这样的:

System.Reflection.PropertyInfo pi = Product.GetType().GetProperty("ProductID");
System.Reflection.PropertyInfo desc = Product.GetType().GetProperty("Description");
System.Reflection.PropertyInfo price = Product.GetType().GetProperty("Price");

int _ProductID = (int)(pi.GetValue(Product, null));
string _Description = (string)(desc.GetValue(Product, null));
decimal _Price = (decimal)(price.GetValue(Product, null));

这可以工作并获取三个字段的正确值。

我习惯于循环数据表,但我只是认为可能有更好的方法来获取这些值。

这是正确的方法还是我错过了什么?在询问之前,我实际上也阅读了文档并弄乱了整个早上。

我看到的一些东西似乎非常复杂。我认为 Dapper 应该简化事情。

最佳答案

好的,谢谢马克。我很难看出 Dapper 类文件中应该有什么以及我的代码中应该有什么。通过 ID 获取产品的原始演示方式的查询为 .FirstOrDefault();

我更改了所有内容以返回列表<>并且一切正常。我确信我的 ADO.NET 正在显示,但这有效。在 Dapper 类文件中:

 public List<Product> ProductAsList(int Id)
        {
            return this._db.Query<Product>("SELECT * FROM Cart_product WHERE ProductID=@Id", new { Id = Id }).**ToList()**;
        }

这只是获取与 ProductID 匹配的一行。

在页面代码隐藏中:

protected void CartItemAdd(string ProductId) // passing it the selected ProductID
    {

        var results = cartservice.ProductAsList(Convert.ToInt32(ProductId));

//使用 Dapper ProductAsList(ProductId) 返回这一行

        int _ProductId = 0;
        string Description = string.Empty;
        decimal Price = 0;

//循环遍历列表并获取每一项的值:

        foreach (Product obj in results)
        {
            _ProductId = obj.ProductID;
            Description = obj.Description;
            Price = obj.Price;
        }

//使用Dapper将选中的商品插入购物车(表格):

        String UserName = "jbanks";

        cartitem = new CartItem();
        cartitem.ProductID = _ProductId;
        cartitem.Quantity = 1;
        cartitem.Description = Description;
        cartitem.Price = Price;
        cartitem.Created = DateTime.Now;
        cartitem.CreatedBy = UserName;
        result = cartservice.AddCartItem(cartitem);

        if (result)
        {
            lblMessage.Text = string.Empty;
            lblMessage.Text = "Successfully added a cart item";
        }
    }


}

它确实从一个表中查找产品并将所选项目插入到另一个表中。

再次感谢!

关于asp.net - Dapper 问题。从返回的对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508996/

相关文章:

asp.net - ASP.NET 表单例份验证的工作原理 : recognising cookies from request

javascript - 递归 trim 对象中所有元素的更好方法?

c# - Dapper 或 MySql 找不到包含句号的存储过程 "."

c# - Dapper Multiple Query Read 很慢

sql - 在 Play-Scala 中使用什么 SQL 访问层进行简单读取?

asp.net - 如何从代码隐藏更改 CSS 类?

ios - 从 IOS 将图像发送到 asp.net web 服务

php - 我应该使用关联数组还是对象?

asp.net - 将 Expression Web 与 ASP.Net MVC 结合使用

php - 为什么在 PHP 中是 'Array()' 而不是 'new Array()'?