c# - Generically return an item from Entity Framework -
i have situation website can ask data database based on string (don't worry - i'm protecting against sql injections). various reasons, have single method returns object (from ef) user expects (which, ultimately, comes through partial page).
i'm thinking this:
public <generictype?> getobject(int id, string typename) { switch(typename) { case "type1": return db.type1s.singleordefault(t => t.typeid == id); case "type2": return db.type2.singleordefault(t => t.typeid == id); default: return null; } }
is possible this? (what trying avoid having switch statement earlier , call specific repository method because have repeat code , number of times.)
createquery<t>
might need.
is there way can possible types you'd passing in comport particular interface has typeid property on it? if so, how about:
public t getresult<t>(int id, string typename) t : iclasswithtypeid { yourentities db = new yourentities(); var result = db.createquery<t>(string.format("[{0}]", typename)); return result.single(t => t.typeid == id); }
Comments
Post a Comment