Dan*_*ngs 5 c# generics entity-framework
我希望能够使用类型为T的通用服务类,该类将允许我动态查询数据库。例如。通常我会做这样的事情来删除记录
public void Delete(Post post)
{
this._context.Posts.Remove(post);
}
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这一点
public void Delete(T post)
{
this._context<T>.Remove(post);
}
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一篇有关它的文章,但如果不是实现它的一种干净方法。https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/
你需要 DbContext.Set
https://msdn.microsoft.com/en-us/library/gg679544(v=vs.113).aspx
返回一个非泛型 DbSet 实例,用于访问上下文和底层存储中给定类型的实体
public void Delete<T>(T post)
where T : class
{
this._context.Set<T>.Remove(post);
}
Run Code Online (Sandbox Code Playgroud)
稍后,您还可以根据以下内容进行查询:
this._context.Set<T>.AsQueryable().Where(predicate);
Run Code Online (Sandbox Code Playgroud)
在这种情况下predicate将是Expression<Func<T, bool>>
所以你可以有一个通用的查询方法:
public IEnumerable<T> Query<T>(Expression<Func<T, bool>> predicate)
where T : class
{
return this._context.Set<T>().AsQueryable().Where(predicate).ToList();
}
Run Code Online (Sandbox Code Playgroud)
......但我现在稍微偏离了这个问题!