如何添加扩展方法
how to add an extension method
首先,我在各种控制器方法中调用 getall() 方法,然后使用 linq 查询仅获取活动用户。但是我想制作一个通用函数,它可以同时从各个表中获取所有活动的属性。这样我就只能调用那个特定的 "getallwhere" 方法。
public IEnumerable<TEntity> GetAllWhere(TEntity entity)
{
return Context.Set<TEntity>().Where(c=>c.isActive == true)
}
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> GetAllWhere();
}`
您正在寻找如下扩展方法:
public static class RepositoryExtension
{
public static IEnumerable<TEntity> GetAllWhere(this Repository repository)
{
return repository.GetAll().Where(x => x.isActive);
}
}
要创建扩展方法,您必须声明一个静态方法 class 并定义一个将 this 作为第一个参数的静态方法。
然后您可以使用您的方法,就好像它存在于原始类型中一样。
myRepository.GetAllWhere();
你可以查看文档ExtensionMethods
public IEnumerable<TEntity> GetAllWhere(TEntity entity)
{
return Context.Set<TEntity>().Where(c=>c.isActive == true)
}
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> GetAllWhere();
}`
您正在寻找如下扩展方法:
public static class RepositoryExtension
{
public static IEnumerable<TEntity> GetAllWhere(this Repository repository)
{
return repository.GetAll().Where(x => x.isActive);
}
}
要创建扩展方法,您必须声明一个静态方法 class 并定义一个将 this 作为第一个参数的静态方法。
然后您可以使用您的方法,就好像它存在于原始类型中一样。
myRepository.GetAllWhere();
你可以查看文档ExtensionMethods