Implementing Generic Service for CRUD operations using EF6

c# entity-framework entity-framework-6 generics repository-pattern

Question

I've done multiple projects using the Repository pattern(Interface=>Repository)but now, I'm facing a new challenge(not a big one) with one of my coworker's code. We are implementing a Generic service that contains all of the CRUD operations methods for all entity classes.

We are using Database first in this project, and have the following structure,

aspx.cs > entityclass(AppUser) > Generic Service > Entity model.

   public class UserServices : GenericServices<User>
   { //Implemented methods }

And this as the Generic Service:

public class GenericServices<T> where T : class
{
    App_dbEntities _db;
    IDbSet<T> ent;

    public GenericServices()
    {
        _db = new App_dbEntities();
        ent = _db.Set<T>();
    }

    public IEnumerable<T> Select()
    {
        return ent;
    }

    public T Select(string id)
    {
        ??
    }
}

I'm trying to handle the entities's properties but since this is Generic, it doesn't know what entity am handling at the moment. I've seen some examples using predicate as a function parameter. Please give me a hand.

1
3
4/13/2016 4:28:40 PM

Accepted Answer

If you want flexibility and are willing to use expressions as your predicate

public virtual T Select(Expression<Func<T, bool>> predicate)
{
    return _dbSet.FirstOrDefault(predicate);
}

Usage

var service = new AppUserServices();
var appUser = service.Select(s=> s.CompositeKey1 == "some_value" && s.CompositeKey2 == "some_other_value");
var appUser2 = service.Select(s=> s.IntProperty == 100 && s.AnotherStringProperty == "some_other_value");
3
4/13/2016 2:29:34 AM

Popular Answer

Agreed with @Thomas, you can use Find method as I show below:

public virtual T Select(params object[] keyValues)
{
  return ent.Find(keyValues);
}

This way you can also find entities with composite primary keys. I suggest to take a look to this codeplex project, you will find an implementation of Repository, UnitOfWork, and also Service pattern. It's going to give you good ideas.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow