ef4 code only - Retrieving an Entity Object by name - LINQ to Entities, EF 4.0 -
i have number of entity objects structurally same naming convention different e.g products1, products2, products3 (this part of legacy db schema , can't this).
these classes of different types far clr concerned , unfortunately since design code auto-generated can't slap interface on these guys show commonality. so, question is: there way retrieve entity object name?
i'd avoid switch/case business when applying same logic these objects.
you build expression tree query object or objects in question:
public t getsingleobject<t>(int somevalue) { myentities db = new myentities(); var result = db.createquery<t>(string.format("[{0}]", typeof(t).name + "s")); var param = expression.parameter(typeof(t)); var lambda = expression.lambda<func<t, bool>>( expression.equal( expression.property(param, "whateverpropertyyourcomparing"), expression.constant(somevalue)), param); return result.singleordefault(lambda); }
or if want collection of objects
public ienumerable<t> getresultcollection<t>(int somevalue) { myentities db = new myentities(); var result = db.createquery<t>(string.format("[{0}]", typeof(t).name + "s")); var param = expression.parameter(typeof(t)); var lambda = expression.lambda<func<t, bool>>( expression.equal( expression.property(param, "whateverpropertyyourcomparing"), expression.constant(somevalue)), param); return result.where(lambda); }
of course if desired query long, can out of hand, , should consider adding in necessary interface using partial classes, justin morgan suggested.
note method assumes objectset collection same name object, plus "s", ie, "invoice" "invoices". if that's not case, ie, "person" "people", use system.data.entity.design.pluralizationservices.pluralizationservice proper name
Comments
Post a Comment