【发布时间】:2019-11-24 18:00:27
【问题描述】:
我有如下的存储库模型。
using System;
using System.Linq;
using System.Linq.Expressions;
using MyProject.DAL.Interface;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace MyProject.DAL.Infrastructure
{
public class BaseRepository<T>: IRepository<T> where T: class
{
private readonly DbContext _dbContext;
private readonly DbSet<T> _dbSet;
public BaseRepository(DbContext context)
{
_dbContext = context ?? throw new ArgumentNullException("Context not be null");
_dbSet = context.Set<T>();
}
public IQueryable<T> GetAll() => _dbSet;
public IQueryable<T> GetAll(Expression<Func<T, bool>> predicate) => _dbSet.Where(predicate);
public T Get(Expression<Func<T, bool>> predicate) => _dbSet.Where(predicate).SingleOrDefault();
// ....
}
}
我有如下服务代码
using System;
using System.Linq;
using System.Linq.Expressions;
using MyProject.DTO.Extensions;
using MyProject.DAL.Interface;
using MyProject.Service.Interface;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
namespace MyProject.Service.Infrastructure
{
public class BaseService<T, U>: IService<U>
where T: class
where U: class
{
protected IRepository<T> Repository;
protected IUnitOfWork UnitOfWork;
public U Get(Expression<Func<U, bool>> predicate) => Repository.Get(predicate); // -> Giving Error
public U GetById(int id) => Repository.GetById(id).MapTo<U>();
public void Add(U entity) => Repository.Add(entity.MapTo<T>());
// ...
}
}
当我想在这样的服务类中使用 Get 方法时;
public U Get(Expression<Func<U, bool>> predicate) => Repository.Get(predicate);
它给出了错误,因为存储库正在等待 T 模型但正在发送服务,U 模型。
如何将谓词类型从 (Expression<Func<U, bool>>) 转换为 (Expression<Func<T, bool>>)?
【问题讨论】:
标签: c# generics lambda type-conversion expression