IQueryable Packaging

I use Entity Framework as my ORM, and each of my classes implements an interface that basically represents table structures (one readonly property for each field). These interfaces are designed to be shared between assemblies for different applications. They do not support any write operations.

Now EF allows me to use instances of IQueryable <EntityClass>. I would like to have support for the IQueryable <IEntityInterface> that will be above it. Needless to say, I expect that I can perform Where operations using the interface properties.

Is this possible at all, or am I wasting my time here? I tried to implement my own IQueryProvider and ExpressionVisitor, but so far this has not turned out so well. I have very little experience with LINQ expression structures. Is it a way to go or is there another, better way?

+4
source share
1 answer

I can’t fully understand what you want to do with this, but the general approach that I saw (and I myself took) is to create a repository using generics. If you set limits on your generics, you can use the interface properties of your entity. Something like that...

public interface IRepository<T> where T : class, IEntityInterface { T FindById(int id); IQueryable<T> All { get; } } public class GenericRepository<T> : IRepository<T> where T : class, IEntityInterface { public T FindById(int id) { //Uses the Id property from the interface return All.Where(t => t.Id == id).Single(); } public IQueryable<T> All { get { //Get DbContext instance from somewhere return _dbContext.Set<T>(); } } } public interface IEntityInterface { int Id { get; } } 

Then you can move on to additional generics, making the interface of the entity also universal. And all this works well with dependency injection and / or factory pattern (if you are at that).

+3
source

Source: https://habr.com/ru/post/1490579/


All Articles