我已经使用 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)
{
??
}
}
我正在尝试处理实体的属性,但由于这是通用的,所以它不知道目前正在处理什么实体。我见过一些使用谓词作为函数参数的示例。请帮帮我。
最佳答案
如果你想要灵 active 并且愿意使用表达式作为你的谓词
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");
关于c# - 使用 EF6 为 CRUD 操作实现通用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36586578/