I am new to Entity Framework and I am stuck with the following.
I have an existing database which I have imported into an EDMX model.
Some of my Entities share the same concept of “owner”.
Each entity have a custom name for the “owner”. Sometimes it is named “author”, sometimes “owner”, sometimes in French “auteur”.
So I have implemented a simple Interface and created partial classes so my Entities could all share the same named concept of “owner”.
public interface IAPIResource
{
int owner { get; }
}
And my partial class for the entity BlogPost
public partial class BlogPost : IAPIResource
{
public int owner { get { return auteur; } }
}
Now I want to use it in LINQToEntities query but LINQ tells me that’s not possible because IAPIResource is not an entity type !
public List<T> GetFilteredEntities<T>(int owner, IQueryable<T> entities, MyDBContext db)
{
return entities.Where(e => ((IAPIResource)e).owner == owner).ToList();
}
I have tried with Reflection (.GetType and .GetProperty and .GetValue) but LINQ does not support that either.
I have tried with POCOs as well, but no much luck.
And I don’t want to modify my DB model with abstract entities and so on.
Does anyone have a simple solution without diving into LINQ Expression ?
NB : the real query is much more complex, that’s why I am not willing to use Expression.
Thank you.
Entity Framework does not support an explicit cast to
IAPIResource, but you don’t need it, you should be able to just doHowever, this does require that you map your
ownerproperty in the implementing classes. You currently havebut that won’t work, because Entity Framework won’t see that
ownerandauteurare the same property. You do need to change this slightly; my personal preference would be to turn this around: makeauteura wrapper property forownerinstead of the other way around. That way, you can continue usingauteurin your code, andownerin queries.