How to create a Generic lambda expression. Many of my entities perform the same Lambda expression predicate
I use Entity Framework 4.
How can I perform a Generic Where Lambda Clause.?I Have many Entity that need the same Where开发者_如何学运维 Query.
public Func<SupplierTypeText, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
public Func<ProductText, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
public Func<CategoryText, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
I would like to have a generic method like
//public interface IRepository<T> : IRepository<T> where T : class
public Func<T, bool> GenericGetLmbLang()
{
return (p => p.LangID == 1);
}
For the moment, I hardcoded Language ID == 1, that will be from the user session to make it dynamic.
That's would be very usefull if I Can directly call the GetLmbLang() Directly in the Where clause. var ViewModel = _db.Suppliers.Select(model => new
{
model,
SupType = _db.SupplierTypeTexts.Where(a => GenericGetLmbLang())
});
------UPDATE--------
Here is what I Trying and nothing works. My Base Class public class BaseGenericModel
{
public int LangID { get; set; }
public Func<BaseGenericModel, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
}
My interface is
public interface IBaseRepository<T> where T : BaseGenericModel
{
Func<T, bool> GetLmbLang();
}
public class BaseRepository<T> : IBaseRepository<T> where T : BaseGenericModel
{
public Func<T, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
}
I Can't call this repository form my SupplierTypeText,ProductText,CategoryText. That's doesn't work.
It seems that you have three different types all having the LangID property. I would make them derive from a common base class where this property is defined:
public class BaseClass
{
public int LangID { get; set; }
}
and then have a single method:
public Func<BaseClass, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
An interface containing this property could also be used.
If you want to make it generic you could but you will still need a generic constraint to indicate a common base type if you want to use the LangID
property:
public class SomeRepository<T> where T: BaseClass
{
public Func<T, bool> GetLmbLang()
{
return (p => p.LangID == 1);
}
...
}
精彩评论