开发者

Generic Query with Entity Framework 4. Generic Repository?

开发者 https://www.devze.com 2023-02-14 00:38 出处:网络
This is my Database Structure : Company CompanyID CompanyName ... Location LocationID LocationName ... Contact

This is my Database Structure :

Company

CompanyID

CompanyName

...

Location

LocationID

LocationName

...

Contact

Conta开发者_高级运维ctID

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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消