【发布时间】:2016-06-22 10:05:21
【问题描述】:
我正在尝试使用数据传输对象和单独的数据提供者构建一个实体框架抽象存储库。我们需要能够根据安装在 oracle、sql server 和 azure sql 之间切换。
最终存储库将 DTO 返回给消费代码。获取、更新和删除工作正常。我遇到的问题是用于 where 子句等的 lambda。通用存储库不知道来自数据提供者的实际 Entity 对象,因此我无法创建 where lambda。
附:使用 AutoMapper 在 Entity 和 DTO 之间进行转换
//Repository base
public class Repository<TEntity> : IDisposable, IRepository<TEntity> where TEntity : class, IEntity
{
public virtual IList<TEntity> GetList(Func<TEntity, bool> where, params Expression<Func<TEntity, object>>[] navigationProperties)
{
List<TEntity> list;
IQueryable<TEntity> dbQuery = Context.Set<TEntity>();
//Apply eager loading
foreach (Expression<Func<TEntity, object>> navigationProperty in navigationProperties)
dbQuery = dbQuery.Include<TEntity, object>(navigationProperty);
list = dbQuery
.AsNoTracking()
.Where(where)
.ToList<TEntity>();
return list;
}
}
//Implementing repository where T is the entity from the EF model
public class UserRepository<T> : IUserRepository, IUnitOfWork
where T : class, IEntity
{
public Repository<T> Base { get; private set; }
public UserRepository(DbContext context)
{
Base = new Repository<T>(context);
}
public List<UserAccountDTO> GetList(Expression<Func<UserAccountDTO, bool>> where)
{
T obj = SupportedRepos.DTOMapper.Map<T>(where.Parameters[0]);
/* HOW CAN I CONVERT THE FUNC<>? */
//Base.GetList();
return null;
}
}
public void TestMethod1()
{
var dbtypeFromConfig = RepoEF.Setup.StorageType.SQLServer;
using (var repo = RepoEF.Setup.SupportedRepos.Create(dbtypeFromConfig))
{
//WORKS FINE, CHANGES AND UPDATES
var source = repo.Get(3);
source.LookupId = 111111;
repo.Add(source);
//CAN'T CREATE WHERE BECAUSE UserRepository<T> ONLY SEES IEntity
repo.GetList(x => x.UserAccountId == 3);
}
}
是否可以构建一个 Func 以传递给基础存储库。
如果没有任何想法,我该如何更改设计以实现我的需要?
【问题讨论】:
标签: c# entity-framework repository dto