Nicolas Faugout
Nicolas Faugout

Reputation: 67

EF EntityObject dynamic property access

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.

Upvotes: 1

Views: 855

Answers (1)

user743382
user743382

Reputation:

Entity Framework does not support an explicit cast to IAPIResource, but you don't need it, you should be able to just do

public List<T> GetFilteredEntities<T>(int owner, IQueryable<T> entities, MyDBContext db)
    where T : class, IAPIResource
{
    return entities.Where(e => e.owner == owner).ToList();
}

However, this does require that you map your owner property in the implementing classes. You currently have

public int owner { get { return auteur; } }

but that won't work, because Entity Framework won't see that owner and auteur are the same property. You do need to change this slightly; my personal preference would be to turn this around: make auteur a wrapper property for owner instead of the other way around. That way, you can continue using auteur in your code, and owner in queries.

Upvotes: 2

Related Questions