如何在实体框架中的 Set<> 方法中使用用户
本文关键字:方法 用户 实体 框架 Set | 更新日期: 2023-09-27 18:33:24
我有一个这样的UnitOfWork
界面:
public interface IUnitOfWork
{
//some other methods
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
}
并像这样实现它:
public class StoreContext : DbContext, IUnitOfWork
{
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
}
我使用Set
方法,我像这样服务层:
public class BrandService : IBrandService
{
private readonly IUnitOfWork _uow;
private readonly IDbSet<Brand> _brands;
public BrandService(IUnitOfWork uow)
{
_uow = uow;
_brands = _uow.Set<Brand>();
}
}
我想在设置方法后在服务层中使用,如下所示:
_brands = _uow.Set<Brand>().Where(row=>row.IsActive == true);
但它返回一个错误:
无法将类型"System.Linq.IQueryable"隐式转换为"System.Data.Entity.IDbSet"
我该怎么做?
我在谷歌上搜索,但找不到类似的问题。
我使用了这段代码:
_uow = uow;
_brands = _uow.Set<Brand>();
var data = _uow.Set<Brand>().Where(e => e.IsDeleted == false);
_brands = (IDbSet<Brand>)data.ToList();
但它返回buildPlan.Cs
未找到
您不能将IQueryable
分配给IDbSet
。将您的声明更改为
private IQueryable<Brand> _brands;
Romanoza Tahnks 为您的答案。如果我在 Service Constructor
中过滤 IsActive
等于 True
的所有行的数据,我无法向用户显示IsActive =false
的所有行,为此我渴望像这样的执行方法:
public static IQueryable<TEntity> ACtive<TEntity>(this IDbSet<TEntity> set) where TEntity : BaseEntity
{
return set.Where(row=>row.IsActive==true);
}
在我需要的地方,我只是像这样调用Active
方法:
public async Task<Brand> GetAsync(Guid brandId)
{
return await _brands.Active().Where(row => row.Id == brandId).FirstOrDefaultAsync();
}
public async Task<IEnumerable<Brand>> GetAllAsync()
{
return await _brands.Active().ToListAsync();
}
我认为这更好.你有什么意见?