如何使用Func类型的表达式调用方法作为参数 [英] How to call method with Expression of type Func as parameter

查看:217
本文介绍了如何使用Func类型的表达式调用方法作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了我在线教程中看到的Repository模式...

I used Repository pattern that I saw on online tutorial...

除了find方法,一切都很正常,我不知道如何使用这个和我很难理解表达式或Func类型。我以前使用过linq和lambda,但我很开心,仍然不会流利地使用它。

Everything works fine except for find method, I have no idea how to work with this and I'm having hard time understanding Expressions or Func types. I used linq and lambda before but I'm begginer and still don't use it fluently...

public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
    return Context.Set<TEntity>().Where(predicate);
}

我有这个模特类:

public partial class Artikl
{
        [Browsable(false)]
        public int IDArtikli { get; set; }
        public string Barkod { get; set; }
        [DisplayName("Šifra")]
        public Nullable<int> Sifra { get; set; }
        public string Naziv { get; set; }
        [DisplayName("JM")]
        public string JedinicaMjere { get; set; }
        public decimal Tarifa { get; set; }
        [DisplayName("Prodajna")]
        public Nullable<decimal> ProdajnaCijena { get; set; }
        [Browsable(false)]
        public Nullable<bool> Flag { get; set; }
        public Nullable<decimal> Kalo { get; set; }
        [DisplayName("Nabavna")]
        public Nullable<decimal> NabavnaCijena { get; set; }
        [DisplayName("Veleprodajna")]
        public Nullable<decimal> VeleprodajnaCijena { get; set; }
        public Nullable<decimal> Zalihe { get; set; }
 }

我的问题是如何根据属性获取Artikl项目Sifra 。我不知道如何调用这个方法...

My question is how can I get the Artikl item based on property "Sifra". I have no idea how to call this method...

private void txtSifra_TextChanged(object sender, EventArgs e)
{
     var artikl = _UnitOfWork.Artikl.Find(???);
     txtNaziv.Text = artikl.Naziv;
}


推荐答案

您需要传递<一个href =https://msdn.microsoft.com/en-us/library/bb397687.aspx =nofollow noreferrer> lambda表达式以满足 Expression< Func< TEntity ,bool>>>谓词。您可以通过以下方式获取基于属性Sifra的项目:

You need to pass a lambda expression to satisfy Expression<Func<TEntity, bool>> predicate. You can get the item based on property "Sifra" by doing this:

var artikl = _UnitOfWork.Artikl.Find(q => q.Sifra == "some int value").FirstOrDefault();

希望它有帮助!

这篇关于如何使用Func类型的表达式调用方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆