作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在做一个项目。它遵循“工作单元”模式。我想编写一个动态方法,我将在其中传递表名,它将返回主键列的最大值,或者我将传递表和列名,它将返回该列的最大值。它看起来像这样——
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/
我是一名优秀的程序员,十分优秀!