c# - 使用泛型的列的最大值

标签 c# linq generics lambda generic-programming

我正在做一个项目。它遵循“工作单元”模式。我想编写一个动态方法,我将在其中传递表名,它将返回主键列的最大值,或者我将传递表和列名,它将返回该列的最大值。它看起来像这样——

public int GetMaxPK<T>()
{
    GetMaxId= ??
    return GetMaxId;
}

这可能吗?我怎样才能做到这一点?或者有什么建议?

最佳答案

在我的项目中,我在 mvc Controller 中这样写来获取 maxId——

public class PurchaseOrderController : Controller
{    
   private IPurchaseOrder interfaceRepository;

    public PurchaseOrderController()
    {
        if (interfaceRepository==null)
        {
            this.interfaceRepository= new Repository();
        }
    }
    int maxId=interfaceRepository.GetMaxPK(a=>a.POMSTID);
}

这里

a=>a.POMSTID

是你要查询的列选择器。假设你想选择名为“PODETID”的列,那么列选择器将是这样的--

a=>a.PODETID

现在在界面中--

    public interface IPurchaseOrder:IRepository<PURCHASEORDERMASTER>
    {

    }

这里“PURCHASEORDERMASTER”是我的查询表或 TEntity。

public interface IRepository<TEntity> where TEntity : class
{
    int GetMaxPK(Func<TEntity, decimal> columnSelector);
}

现在在调用数据库的存储库(或具体)类(继承接口(interface))中,您必须像这样写--

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
 {   

    public int GetMaxPK(Func<TEntity, decimal> columnSelector)
    {
        var GetMaxId = db.Set<TEntity>().Max(columnSelector);
        return GetMaxId;
    }
 }

这里的 db 是数据库上下文,decimal 是我的查询列的数据类型。

关于c# - 使用泛型的列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193729/

相关文章:

c# - 使用 emgucv 测量两个图像的差异

c# - 如何使用反射通过构造函数强制转换为对象?

c# - 如何在字典值上强制使用正则表达式模式(njsonschema)

java - 如何在 Bean Validation 1.0 中构造 ConstraintViolationException?

java - 具有 super 泛型的代码无法按预期工作

c# - 替换作为属性/公共(public)字段检索的对象列表中的元素

c# - 如何将连接两个对象的 LINQ 查询语法转换为方法语法?

c# - LINQ字典到锯齿状数组?

.net - 从表达式中获取类名和属性名 () => MyClass.Name

java - 有没有实现 Iterable 而不实现 Collection 的 Java 标准类?