使用泛型的列的最大值

Max value of a column using generics

我正在处理 project.It 的后续 "Unit of work" pattern.I 想编写一个动态方法,我将在其中传递 table 名称,它将 return 主键列的最大值,否则我将传递 table 和列名,它将 return 该列的最大值。它看起来像这样--

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

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

您可以定义具有一个属性的 interface

public interface IMax
{
    int Id { get; set; }
}

然后你的通用 class 应该实现这个接口:

public class yourClass<T> where T : class , IMax

最后:

public int GetMaxPK()
{
    GetMaxId= yourTable.Max(c => c.Id);
    return GetMaxId;
}

你的完整代码应该是这样的:

public class yourClass<T>  where T : class, IMax
{
    public int GetMaxPK(IEnumerable<T> yourTable)
    {
        var GetMaxId = yourTable.Max(c => c.Id);
        return GetMaxId;
    }
}

您可以考虑使用类似于 Max 扩展方法的方法

TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);

根据您的情况进行调整

public int GetMaxPK<TTable>(IEnumerable<TTable> table, Func<TTable, int> columnSelector) {
    var maxId= table.Max(columnSelector);
    return maxId;
}

或者假设源代码已经在封装内部 class 例如 DbContext

DbContext db;

//...

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

并称赞

var maxId = myClass.GetMaxPK<TableName>(t => t.PKColumnName);

在我的项目中,我在 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

是列 select 或者你想要 query.Suppose 你想要 select 列命名为 "PODETID" 然后列 selector 会像这样--

a=>a.PODETID

现在在界面中 --

    public interface IPurchaseOrder:IRepository<PURCHASEORDERMASTER>
    {

    }

这里 "PURCHASEORDERMASTER" 是我的查询 table 或 TEntity。

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

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

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 是我查询列的数据类型。