使用 EF6 为 CRUD 操作实现通用服务

Implementing Generic Service for CRUD operations using EF6

我已经使用 Repository 模式(Interface=>Repository)完成了多个项目,但现在,我面临着一个新的挑战(不是很大的挑战)我的一个同事的代码。我们正在实施一个通用服务,其中包含所有实体 类 的所有 CRUD 操作方法。

我们在这个项目中首先使用数据库,并具有以下结构,

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

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

这是通用服务:

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)
    {
        ??
    }
}

我正在尝试处理实体的属性,但由于这是通用的,所以它不知道目前正在处理什么实体。我见过一些使用谓词作为函数参数的例子。请帮帮我。

同意@Thomas,您可以使用Find方法,如下所示:

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

这样您还可以找到具有复合主键的实体。 我建议看看这个 codeplex project,你会发现 RepositoryUnitOfWork 的实现,还有 服务模式。它会给你好主意。

如果您想要灵活性并愿意使用表达式作为谓词

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

用法

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");