Ronald Rozema
Ronald Rozema

Reputation: 246

asp.net Generic repository find by property

I am using Generic Repositories with ASP.NET. Now I am trying to find an object by the user Id which requires to access a property of the class, but ofcourse in the linq expression the property is not know, because it does not know the type yet. Is there any way around this?

public virtual IEnumerable<T> GetByUser(string userId)
    {
        if (typeof(T).GetProperty("Employee") != null)
        {
            return Db.Set<T>().Where(x => x.Employee.Id == userId);
        }
        return new List<T>();
    }

the "x.Employee.Id" gets the error that there is no definition of Employee. That is to be expected. Do I need to do this in an entire different way or does somebody knows how to fix this?

I hope anybody can help!

Upvotes: 0

Views: 1801

Answers (1)

JEV
JEV

Reputation: 2504

Use interfaces so that you know T will have certain properties. Or use a base type and then use constraints on the generic parameter.

public virtual IEnumerable<T> GetByUser(string userId) where T : IEmployee
{
   return Db.Set<T>().Where(x => x.Employee.Id == userId);
}

And where IEmployee looks like this

public interface IEmployee 
{
    Employee Employee { get; set; }
}

Obviously this is a bit crude, but depending on your entities this could be an approach. You could always map out everything and then build up your interfaces for the shared properties etc.

However to be honest I think your best approach is to have a more functional set of generic repositories. For example a base repo, and then an EmployeeRepostiory that knows that T will be an Employee.

MSDN Article on Constraints

Upvotes: 1

Related Questions