I’m converting from LINQ to SQL to Entity Framework for my ORM and I’m updating my repositories. All of them are done except for the generic one. I can’t seem to figure out how to convert my Select method from what it is now to one that works with EF. Here’s the current code:
public T Select(int Id)
{
MetaDataMember PrimaryKey = this.DataContext.Mapping.GetTable(typeof(T)).RowType.DataMembers.SingleOrDefault(
d =>
(d.IsPrimaryKey));
ParameterExpression Param = Expression.Parameter(typeof(T), "e");
var Query = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(Param, PrimaryKey.Name), Expression.Constant(Id)), new ParameterExpression[] { Param });
return this.DataContext.GetTable<T>().Single(Query);
}
I didn’t write this, I copied it from some person’s blog and it’s worked for me so far. I really don’t know what it does, vague idea, but I’m not capable of translating it to EF.
So, I’ve come here to ask for the assistance of you fine ladies or gentlemen. If possible, I’d love it if someone who knows EF can convert that statement. If there’s alternative code to accomplish the same thing, I’m open to it.
If i understand that method correctly, it returns a single record for any type T, based on a primary key.
We also have a generic repository, but the interface looks like this:
And our generic repository implementation:
So to get the equivalent single record for a “Post”:
That’s a lot different to your original code – as the calling code is specifying what the primary key is (or a way to identity a unique record).
To be honest, trying to dynamically grab a unique record based on a constant primary key value is pretty crazy – what if it’s a composite key? I can’t see how that code would work.
Happy to see other answers, but i would keep it simple.
If you want the code to grab the entity set based on T, i can share that – but it’s pretty simple.
If you want a method to grab a single record, let the calling code supply the predicate/key:
Then if for example “Post” had a composite key of “PostName” and “PostType”:
In your example, your repository is dictating your model, making each entity have a single column primary key.
Your repository should aid your model, not define it.
EDIT – Code for
GetEntitySet<T>, as requestedPretty simple, and quite safe, because
_plularizeris of typeSystem.Data.Entity.Design.PluralizationService, which is the same module that EF uses to create default entity set names.EntityContainerNameis your container name for your entities.Your
_plularizerinstance should be static, and kept thread-safe with a fully-locked singleton.HTH.