Search code examples
c#entity-frameworkentity-framework-5entitykey

SqlQuery EntityKey and return corresponding object


I would like to query my database based on a EntityKey is there a inbuild (or easier approach) to do this?

My current approach, would be something like this:

using (var context = new DbContext())
{
    context.DataBase.SqlQuery<TestTable>("select * from @p0 where @p1 = @p2", EntityKey.EntitySetName, EntityKey.EntityKeyValues[0].Name, EntityKey.EntityKeyValues[0].Value);
}

(This solution currently has the problem, that the EntitySetName isnt the TableName and I would need to grab the TableName out of the MetaData, same with the Name of the Id which could also be different than database)

Or is there even a way to do this with LINQ? (which I would prefer, since I wouldnt need to manually translate)


Solution

  • If you know the type of the entity you're retrieving, you can use the Set method on DbContext to get a DbSet, and the Find method on DbSet to get an entity by its key(s).

    var dbSet = dbContext.Set<TestTable>();
    var entity = dbSet.Find(EntityKey.EntityKeyValues[0].Value);
    

    The Find method knows how to turn use the key value to get an entity; in fact, the signature is Find(params object[]) so you can pass in multiple key values if your table has a composite key (as long as they're in the right order).