I am new to asp.net and creating a MVC project using entities framework. Mostly it work as I expected but have an issue where I need to pass parameters to a method which could be of different types. I need this because I dont want to write same method in each class which send same results. Here is my setup
public class BaseQuery : IOSSQuery
{
private Entities dbcontext;
public BaseQuery() : this(new Entities())
{
}
public BaseQuery(Entities context)
{
this.dbcontext = context;
}
public List<SimpleItem> GetAllItemsFromQuery<T>( T table,Int32 skip)
{
List<SimpleItem> SimpleItemList = new List<SimpleItem>();
SimpleItemList = table.Where(p => p.IsActive == true).OrderBy(p => p.Name).Select(p => new SimpleItem { id = p.Id, Name = p.Name, IsActive = p.IsActive }).Skip(skip).Take(30).Distinct().ToList();
return SimpleItemList;
}
public virtual List<SimpleItem> GetAllItems(Int32 skip)
{
List<SimpleItem> SimpleItemList = new List<SimpleItem>();
return SimpleItemList;
}
}
Then I have a query class,
public class ColorQuery : BaseQuery
{
public override List<SimpleItem> GetAllItems(Int32 skip)
{
return GetAllItemsFromQuery( dbcontext.tbl_color, skip)
}
}
Here is the interface
public interface IOSSQuery : IDisposable
{
List<SimpleItem> GetAllItems(Int32 skip);
}
I would like to call the method from my controller as following
public JsonResult Color(String range)
{
ColorQuery query = new ColorQuery();
List<string> ranges = range.Split(',').ToList<string>();
var SimplePage = getAllItems(query, Convert.ToInt32(ranges[0]));
return Json(SimplePage, JsonRequestBehavior.AllowGet);
}
public PagedData<SimpleItem> getAllItems( IOSSQuery queryObject, int range )
{
var SimplePage = new PagedData<SimpleItem>();
SimplePage.total = queryObject.TotalItems();
SimplePage.data = queryObject.GetAllItems(range);
return SimplePage;
}
This code throw error at this line in BaseQuery class
public List<SimpleItem> GetAllItemsFromQuery<T>( T table,Int32 skip)
Error CS1061 'T' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
Not sure how do I pass different types in the method. I tried solution from Method to accept different types without luck. Can anybody shed lights on this. Thanks for your time.
Edits: This is how it setup in my entities
public DbSet<tbl_Category> tbl_Category { get; set; }
public DbSet<tbl_color> tbl_color { get; set; }
EDIT 2:
I have multiple tables with different columns. My idea is to use generic method from "BaseQuery" for all tables which returns same result still want to use "ColorQuery" or say "CategroyQuery" class for different query if I need.