Search code examples
asp.net-mvc-2entity-framework-4repository-patterngeneric-programming

Generic Query with Entity Framework 4. Generic Repository?


This is my Database Structure :
Company
CompanyID
CompanyName
...

Location
LocationID
LocationName
...

Contact
ContactID
ContactName
ContactEmail

CompanyContact
ContactID
CompanyID
IsActive

LocationContact
ContactID
LocationID
IsActive

Now I have a repository for each of these entity (CompanyContact, LocationContact)

public List<Contact> GetCompanyContact(int CompanyID)
{
   return _context.CompanyContacts.Where(p => p.CompanyID == CompanyID).Select(s => s.Contact).ToList();
}
...
public List<Contact> GetLocationContact(int LocationID)
{
   return _context.LocationContacts.Where(p => p.LocationID == LocationID).Select(s => s.Contact).ToList();
}
...

How Can I create a Generic method to get the List of contact. I would like to pass, the EntityName(CompanyContact or LocationContact) with the Reference Column name(CompanyID, LocationID).
Example of What I want :

public List<Contact> GetContact(string EntityName,String ColName){....}
Ex of call .
GetContact("CompanyContact","CompanyID");

Thx a lot.

EDIT
A Company can have Many Contact and a Location can have many contact too.


Solution

  • Presumably, you have your database context in your Repository, so I would use a little bit of generics with a dash of lambda to get something neat, like so:

    public class MyRepository {
        var _context = new MyEFDatabaseEntities();
    
        public List<T> GetListOf<T>(Expression<Func<T, bool>> expression)
            where T : class {
    
            return _context.CreateObjectSet<T>().Where(expression).ToList();
        }
    }
    

    This little one-liner lets you do fun stuff like this:

    // first make a repository object
    var repository = new MyRepository();
    
    // now I can grab a list of contacts based on CompanyID
    var contacts = repository.GetListOf<Contact>(c => c.ContactID == 12345);
    
    // or I can get a list of contacts based on location
    var contacts = repository.GetListOf<Contact>(c => c.LocationID == 12345);
    
    // get all contacts for a company
    var contacts = repository.GetListOf<CompanyContact>(c => c.CompanyID == 123).Contacts;
    
    // get all confabs for a location
    var contacts = repository.GetListOf<LocationContact>(c => c.CompanyID == 123).Contacts;