问题
Hi all I am trying to filter the table using where class by passing parameter to the method like as below,
private IQueryable<SpaceFunctionType> Get<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, ICategorySpaceFunction
{
return _dbContext.Set<TEntity>().Where(predicate)
.Select(c => new SpaceFunctionType
{
Category = c.Category,
SpaceFunction = c.SpaceFunction
});
}
public IQueryable<SpaceFunctionType> GetSpaceFunctionType(string environmentSource)
{
return Get<LibraryEnvironment>(x => x.EnvironmentSource.Name == environmentSource).AsQueryable();
}
and these are the interface details,
public interface ICategorySpaceFunction
{
public string Category { get; set; }
public string SpaceFunction { get; set; }
}
and this will be the class name
public class SpaceFunctionType : ICategorySpaceFunction
{
public string Category { get; set; }
public string SpaceFunction { get; set; }
}
but getting an error here Get<LibraryEnvironment> like as below
The type 'API.DesignHub.Entities.LibraryEnvironment' cannot be used as type parameter 'TEntity' in the generic type or method 'Query.Get(Expression>)'. There is no implicit reference conversion from 'API.DesignHub.Entities.LibraryEnvironment' to 'API.DesignHub.Entities.ICategorySpaceFunction'
I am not sure where i am doing wrong with the above method, Could any one please suggest any idea on this that would be very grateful to me,
Many thanks in advance
回答1:
The error is what it is happening. But the language used there is a bit generic. What it means is LibraryEnvironment does not implement ICategorySpaceFunction. TEntity is a type of ICategorySpaceFunction and you are sending LibraryEnvironment when calling, so it is a rule that LibraryEnvironment should be similar to TEntity, which is an implementation of ICategorySpaceFunction. more details - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
来源:https://stackoverflow.com/questions/59868996/getting-an-error-on-trying-to-call-method-in-generic-way