c# - Generic query to get records from different tables -
in our project connecting database linq-to-entities. read valid records ,let's say, table1 there method:
public list<tablename> gettablenamerecords() { try { return (from x in _context.tablename x.valid == 1 select x).tolist(); } catch (exception ex) { throw new exception(ex.message); } }
it works, there problem - each table need write same query , change table name. there way write generic method pass table name? like:
public list<t> getrecords<t>() { try { return (from x in _context.<t> x.valid == 1 select x).tolist(); } catch (exception ex) { throw new exception(ex.message); } }
thanks help
you can use reflection this, you're facing rather ugly code. however, if you're willing change models little bit, can in relatively straightforward way.
create interface has 1 property - valid
, so:
interface ivalid { bool valid { get; set; } }
make sure models have valid field implement interface. can this:
list<t> getvalid<t>(dbcontext context) t: ivalid { return context.set<t>().where(x=>x.valid).tolist() }
by having models implement interface, can use ordinary linq expression , have compiler sort out.
Comments
Post a Comment