Search code examples
c#entity-framework-corerepository-patternanonymous-functionanonymous-types

How to select and return custom properties from a TEntity based on a method parameter


I'm working on an advanced Generic repository targeted .Net 5 and Entity Framework core.

I'm trying to create a method that will receives the properties to be selected from a TEntity and this method should get those properties from the table and return a list of objects their structure is an Anonymous type contains the properties to be selected sent in the parameters.

What I tried :

public virtual object GetPartial<TEntity> ( params Expression<Func<TEntity, object>>[] propertiesToBeSelected )
{
    var result = (from x in Context.Set<TEntity>() select propertiesToBeSelected).ToList();
    return result;
}

How wanna the final use for this method : Let's imagin we have a Student entity and I want to select just a list of name and city from the Student, I want to use the method like this :

MyXRepo.GetPartial<Student>(x => x.Name, x => x.City);

I wish you understood, and sorry for my level in English.

I know this is no a correct way, so please any help to fix this issue ?


Solution

  • IMHO, I don't have a lot of experience and I won't try discuss which pattern is wrong or good :).

    I agree, returned type should be rather List<object> than object itself and I prefer to add this kind of logic to extensions.

    I've tested this code, try yourself and check if fits (of course, ignore controller types )

    public IActionResult Test()
    {
        var result = myService.GetPartial<Company>(x=> new { x.Name1 , x.Notes});
        return Ok();
    }
    

    and the implementation

    public IEnumerable<object> GetPartial<T>(Func<T, object> selector)
                where T:class
    {
        var t = DbContext.Set<T>().Select(selector).ToList();
        return t;
    }
    

    Once again, it is my version what I understood. And it is little more flexible. Instead list of properties method get function returning object whatever type you want.You have to add some extra chars (lambda convention) and cast (if needed), but you can also get strongly typed object or create another implementation

    IEnumerable<TModel> GetPartial<TEntity, TModel>(Func<TEntity, TModel>){... 
    

    Any improvements are welcome