Reputation: 2741
Task: write a generic extension for Entity Framework entities
I am not sure if this is even possible due to the fact that each entity usually will have differing properties, but I have a group of entities that share a few common properties and all I was wondering if it is even possible to build a generic extension instead of always having to write out the same code for each entity.
I spent a bit of time researching this, but there is not much , which leads me to believe this just is not possible.
Anyway, contrary to my better judgment I am going to ask a stupid question on StackOverFlow.
This is what I was thinking, but obviously a non compile-able example, but at least you will get the idea.
public static List<TEntity> Generic<TEntity>(this DbContext db, string name)
{
return db.TEntity.Where(s => s.Name == name);
}
I poke in the right direction would be appreciated.
And just for clarity, I have never spent a single hour in a classroom for programming, I am self taught, so if it is not possible to this, could the answer explain please explain technically why this is not possible in Entity Framework. As I could not find anything substantial myself.
Upvotes: 1
Views: 369
Reputation: 118
Use this
public IEnumerable<TEntity> Filter(Expression<Func<TEntity, bool>> filter, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
db.Set<TEntity>().AsNoTracking().AsQueryable().Where(filter);}
Upvotes: 0
Reputation: 2741
Thanks to @Bagus Tesa, I was able to solve this.
As Bagus tesa states, make an interface
that references the common properties of the Entities
and refference the interface
with the Entities
and make an extension that way.
The code I used,
public static IQueryable<IFilterEntity> FilterEntity(this BaseViewModel vm,
IQueryable<IFilterEntity> list)
{
return list.Where(s => s.Name == vm.name &&
s.DateMonth == vm.Month &&
s.DateYear == vm.Year);
}
The interface,
public interface IFilterEntity
{
string Name { get; set; }
int? DateYear { get; set; }
int? DateMonth { get; set; }
}
The BaseViewModel,
public class BaseViewModel
{
string Name => RootVm.Name;
int? DateYear => RootVm.SelectedDate.Month;
int? DateMonth => RootVm.SelectedDate.Month;
}
Thanks for all the help with. And I hope this helps someone else.
Upvotes: 1