gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:29:23 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com