Search code examples
c#linqgenericslambdageneric-programming

Max value of a column using generics


I am working on a project.It's following "Unit of work" pattern.I want to write a Dynamic method where I will pass the table name it will return the max value of primary key column or I will pass the table and column name it will return the max value of that column. It will look something like this--

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

Is it possible? How can I do this? Or any suggestion?


Solution

  • In my Project,I wrote in mvc controller to get maxId like this--

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

    here

    a=>a.POMSTID

    is the colum selector that you want to query.Suppose you want to select column named "PODETID" then column selector will be like this--

    a=>a.PODETID

    now in interface --

        public interface IPurchaseOrder:IRepository<PURCHASEORDERMASTER>
        {
    
        }
    

    Here "PURCHASEORDERMASTER" is my query table or TEntity.

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

    now in the repository(or concrete) class(that inherit the interface) where you call the db you have to write like this--

    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;
        }
     }
    

    here db is the database context and decimal is the data type of my query column.