[英]How can I convert lambda expression parameter type to another generic type?
我有如下的存儲庫模型。
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>>
) ?
我不知道您傳遞給 U 和 T 的類型是什么,因為您沒有如何填充基類的樣本。 所以我猜一個是實體,另一個是映射到實體的 DTO。 可以編寫動態表達式,調用 mapper 將表達式參數映射到 T 所需的類型,但這會很困難,並且需要反射和表達式惡作劇。 所以我的建議是將您的函數簽名轉換為:
public U Get(Expression<Func<T, bool>> predicate) => Repository.Get(predicate).MapTo<U>;
因為它只是一個表達式,如果映射類型相似,它不會改變你調用函數的方式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.