Home > other >  How can I make a IQueryable of Generic Type in LINQ C#?
How can I make a IQueryable of Generic Type in LINQ C#?

Time:06-30

I have a method that takes an Id with name PcId on basis of that I am trying to retrieve data from different tables , how can I make a generic IQueryable ?

                    IQueryable<T> queryAble = null; 
                    switch (pcType)
                    {
                        case "Pc1":
                            queryAble = _context.Pc1Remarks.Where(x => x.Pc1id == pcId).AsQueryable();
                            break;
                        case "Pc2":
                            queryAble = _context.Pc2Remarks.Where(x => x.Pc2Id == pcId).AsQueryable();
                            break;
                        case "Pc3a":
                            queryAble = _context.Pc3aRemarks.Where(x => x.Pc3aId == pcId).AsQueryable();
                            break;
                        case "Pc3b":
                            queryAble = _context.Pc3bRemarks.Where(x => x.Pc3bId == pcId).AsQueryable();
                            break;
                        case "Pc4":
                            queryAble = _context.Pc4Remarks.Where(x => x.Pc4Id == pcId).AsQueryable();
                            break;
                        case "Pc5":
                            queryAble = _context.Pc5Remarks.Where(x => x.Pc5Id == pcId).AsQueryable();
                            break;
                        default:
                            return Tuple.Create("PC Type is not valid", new List<PcRemarksModel>());
                    }

Right now its giving error on all cases

enter image description here

CodePudding user response:

I would say that based on provided code this is example of how generics should not be used and how they were not supposed to be used. As for workarounds - you can try casting to (IQueryable<T>) (assuming that T is corresponding Pc1Remark, Pc2Remarks ... or how the entities types are called):

IQueryable<T> queryAble = null; 
switch (pcType)
{
    case "Pc1":
         queryAble = (IQueryable<T>)(_context.Pc1Remarks.Where(x => x.Pc1id == pcId));
         break;
    // ... the same in the other cases
}

Though I would repeat - ideally this method should not be generic in the first place.

CodePudding user response:

Unless you have a base class all of the entities you are querying extend, you will want to do

IQueryable<Object> queryAble = null;

When you want to then evaluate the collection and only get of certain types, you will want to do something like

IEnumerable<PC5Remarks> result = queryAble.OfType<PC5Remarks>().Where(...).Select(...).ToList();
  • Related