Make a LINQ query on object implementing interface
See the code below. I'd like do some check on some properties (on IsActive for example). Could you tell me how do this in my case how implement this in the GetList() ?
Thanks,
public interface ILookup
{
int Id { get; set; }
string FR { get; set; }
string NL { get; set; }
string EN { get; set; }
bool IsActive { get; set; }
}
public class LookupA : ILookup
{
}
public class LookupB : ILookup
{
}
public interface ILookupRepository<T>
{
IList<T> GetList();
}
public class LookupRepository<T> : ILookupRepository<T>
{
public IList<T> GetList()
{
List<T> list = Session.Query<T>().ToList<T>();
return list;
} 开发者_如何学Python
}
If you know T
will be of type ILookup
you need to put a constraint on it like such:
public interface ILookup
{
int Id { get; set; }
string FR { get; set; }
string NL { get; set; }
string EN { get; set; }
bool IsActive { get; set; }
}
public class LookupA : ILookup
{
}
public class LookupB : ILookup
{
}
public interface ILookupRepository<T>
{
IList<T> GetList();
}
public class LookupRepository<T> : ILookupRepository<T> where T : ILookup
{
public IList<T> GetList()
{
List<T> list = Session.Query<T>().Where(y => y.IsActive).ToList<T>();
return list;
}
}
You should be able to leverage Generic Constraints to help you out.
First, change your interface definition:
public interface ILookupRepository<T> where T : ILookup
// ^^^^^^^^^^^^^^^^^
Second, change your class definition to match the constraints:
public class LookupRepository<T> : ILookupRepository<T> where T : ILookup
// ^^^^^^^^^^^^^^^^^
The constraint will require the generic type parameter to implement ILookup
. This will let you use the interface members in your GetList
method.
精彩评论