[英]how to cast derived BaseModel have isdelete flag in iqueryable, make soft delete repository in entity framework core
why this does not work and how I can fix it, I want to make soft delete/hard delete using one repository为什么这不起作用以及如何修复它,我想使用一个存储库进行软删除/硬删除
public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>> predicate)
{
var query = Context.Set<TEntity>().Where(predicate);
if (query is IQueryable<BaseModel>)
{
var baseQuery = query as IQueryable<BaseModel>;
query = baseQuery.Where(x => !x.isDelete) as IQueryable<TEntity>;
}
return await query.ToListAsync();
}
this base model class此底座 model class
public class BaseModel
{
public bool isDelete { get; set; }
}
this the model这是 model
public class Jobs : BaseModel
{
public int Id { get; set; }
public string Description { get; set; }
public string ProjectName { get; set; }
public string Project_Status { get; set; }
}
i have this exception我有这个例外
{"Expression of type 'System.Linq.IQueryable`1[Models.BaseModel]' cannot be used for parameter of type 'System.Linq.IQueryable`1[Models.Jobs]' of method 'System.Linq.IQueryable`1[Models.Jobs] Where[Jobs](System.Linq.IQueryable`1[Models.Jobs], System.Linq.Expressions.Expression`1[System.Func`2[Models.Jobs,System.Boolean]])' (Parameter 'arg0')"}
You cannot cast the IQueryable<BaseModel>
to IQueryable<TEntity>
because the IQueryable<out T>
is covariant .您不能将IQueryable<BaseModel>
转换为IQueryable<TEntity>
因为IQueryable<out T>
是covariant 。 So you can only cast from IQueryable of more derived types (eg: TEntity
) to IQueryable of less derived types (eg: BaseModel
).所以你只能从更多派生类型的 IQueryable (例如: TEntity
)转换为更少派生类型的 IQueryable (例如: BaseModel
)。
So here is the solution, you can use .Cast<T>
to cast the element type instead of the whole IQueryable<TEntity>
:所以这是解决方案,您可以使用.Cast<T>
来转换元素类型而不是整个IQueryable<TEntity>
:
public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>> predicate)
{
var query = Context.Set<TEntity>().Where(predicate);
if (typeof(BaseModel).IsAssignableFrom(typeof(TEntity)))
{
query = query.Cast<BaseModel>().Where(e => !e.isDelete).Cast<TEntity>();
}
return await query.ToListAsync();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.