小巧玲珑的问题。从返回的对象中获取值

Dapper question. Getting values from returned object

刚开始学习Dapper。我有 ADO.NET 背景。使用我下载的演示,我可以将网络表单中的 insert/delete 数据转换为 MySql table 就好了。不过这个我已经找了一个上午了。

在通过 ID 从数据库中检索单行时,它不是 return LIST<>,它似乎只是一个对象(使用我下载的演示中的代码)。查询有效,我取回了对象。它具有以下字段:"ProductID, Description and Price".

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

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 应该简化事情。

主要Query<T>APIreturns一个IEnumerable<T>,通常一个List<T>AsList<T>() 扩展方法可以在没有副本的情况下将其返回到列表,但无论哪种方式:它们 只是 T,无论你 T要求。如果您要求 Query<Product>,那么:它们应该是 Product 个实例:

var results = connection.Query<Product>(someSql, someArgs); // perhaps .AsList()
foreach (Product obj in results) { // "var obj" would be fine here too
    // now just use obj.ProductID, obj.Description and obj.Price
}

如果这不起作用:请检查您是否使用了 Query<T> 版本。还有一个非通用变体,returns dynamic。坦率地说,您应该几乎总是使用 <T> 版本。

注意:我假设你有类似

的东西
class Product {
    public int ProductID {get;set;}
    public string Description {get;set;}
    public decimal Price {get;set;}
}

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

我将所有内容更改为 return a List<> 并且一切正常。我确定我的 ADO.NET 正在显示,但这有效。在 Dapper class 个文件中:

 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));

// return 一行使用 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 将所选产品插入购物车 (table):

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


}

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

再次感谢!