如何在泛型方法中反映 lambda 的属性?

发布于 2024-12-18 03:49:24 字数 772 浏览 2 评论 0原文

我需要为我的存储库反映 lambda 的属性,代码如下:

public abstract class RestController<T> : Controller where T : class
{
    private readonly IRepository _db;
    private readonly string _identityProp;

    protected RestController(IRepository db, string identityProp)
    {
        _db=db;
        _identityProp = identityProp;
    }

    protected virtual void Delete(T item)
    {
        var value = item.GetType().GetProperty(_identityProp).GetValue(item, null);
        var items = _db.All<T>()
            .Where(i=>i.GetType().GetProperty(_identityProp)==val)
            .ToList();
        items.ForEach(x=>_db.Delete(x));
        _db.CommitChanges();
        return Json("success");
    }
}

但是 lambda 的结果是一个空列表...请帮忙,我做错了什么?

I need to reflect a property for lambda for my Repository, here's the code:

public abstract class RestController<T> : Controller where T : class
{
    private readonly IRepository _db;
    private readonly string _identityProp;

    protected RestController(IRepository db, string identityProp)
    {
        _db=db;
        _identityProp = identityProp;
    }

    protected virtual void Delete(T item)
    {
        var value = item.GetType().GetProperty(_identityProp).GetValue(item, null);
        var items = _db.All<T>()
            .Where(i=>i.GetType().GetProperty(_identityProp)==val)
            .ToList();
        items.ForEach(x=>_db.Delete(x));
        _db.CommitChanges();
        return Json("success");
    }
}

but the result of lambda is an empty list... Help please, what I'm doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヤ经典坏疍 2024-12-25 03:49:24

您的 LINQ 查询中缺少 .GetValue(i, null)。目前,您正在将属性的值 (value) 与描述该属性的 PropertyInfo 进行比较。

正确的代码:

var items = _db.All<T>()
               .Where(i => i.GetType().GetProperty(_identityProp)
                                      .GetValue(i, null) == val)
               .ToList();

或者,更注重性能:

var propertyInfo = item.GetType().GetProperty(_identityProp);
var value = propertyInfo.GetValue(item, null);
var items = _db.All<T>()
               .Where(i => propertyInfo.GetValue(i, null) == val)
               .ToList();

You are missing a .GetValue(i, null) in your LINQ query. Currently, you are comparing the value of the property (value) with the PropertyInfo describing the property.

Correct code:

var items = _db.All<T>()
               .Where(i => i.GetType().GetProperty(_identityProp)
                                      .GetValue(i, null) == val)
               .ToList();

Or, a little bit more performance orientated:

var propertyInfo = item.GetType().GetProperty(_identityProp);
var value = propertyInfo.GetValue(item, null);
var items = _db.All<T>()
               .Where(i => propertyInfo.GetValue(i, null) == val)
               .ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文