开发者

How to create and return an Expression<Func

开发者 https://www.devze.com 2023-01-19 20:05 出处:网络
I Use entity Framework 4. I would like to be able to create a function that return an Expression func that will be use in a lambda expression.

I Use entity Framework 4.

I would like to be able to create a function that return an Expression func that will be use in a lambda expression.

  var ViewModel = _db.Suppliers.Select(model => new { 
                model,SupType = model.SupplierType.SupplierTypeTexts.Where( st => st.LangID == 1)   
            });

I would like to make this call like that

  var ViewModel = _db.Suppliers.Select(model => new { 
                model,SupType = model.SupplierType.GetText() 
            });

My Partial class is:

  public partial class SupplierType
    {

       public  Expression&开发者_JAVA技巧lt;Func<SupplierTypeText, bool>> GetText()
        {
            return p => p.LangID == 1;
        }

How can i perform this.


Easy. For example, Let's assume you have a Product table that is mapped to Products EntitySet in your context, now you want to pass a predicate and select a Product:

Expression<Func<Product, bool>> GetPredicate(int id) {
    return (p => p.ProductID == id);
}

You can call GetPredicate() with a Product ID to filter based on that:

var query = ctx.Products.Where(GetPredicate(1)).First();

The point really is that you can always pass a Lambda Expression to where an Expression<T> is needed.

EDIT:
You should change your code like this:

var ViewModel = _db.Suppliers.Select(model => new { 
    model,
    SupType = model.SupplierType.SupplierTypeTexts.Where(GetText()) 
});
public Expression<Func<SupplierTypeText, bool>> GetText() {
    return (stt => stt.LangID == 1);
}


If you want to dynamically create compiled Expression at runtime (as opposed to ones hardcoded against a particular data model at compile time) you need to use the static methods on the Expression class.

0

精彩评论

暂无评论...
验证码 换一张
取 消