如何在泛型方法中反映 lambda 的属性?
我需要为我的存储库反映 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 LINQ 查询中缺少
.GetValue(i, null)
。目前,您正在将属性的值 (value
) 与描述该属性的PropertyInfo
进行比较。正确的代码:
或者,更注重性能:
You are missing a
.GetValue(i, null)
in your LINQ query. Currently, you are comparing the value of the property (value
) with thePropertyInfo
describing the property.Correct code:
Or, a little bit more performance orientated: