Rand Random
Rand Random

Reputation: 7440

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)

Upvotes: 1

Views: 351

Answers (2)

Steve Ruble
Steve Ruble

Reputation: 3895

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).

Upvotes: 1

nemesv
nemesv

Reputation: 139758

You can cast your DbContext to the IObjectContextAdapter interface and from there you can access the underlying ObjectContext object which has the GetObjectByKey method:

using (var context = new DbContext())
{
    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
    var entity = objectContext.GetObjectByKey(yourEntityKey);
}

Upvotes: 2

Related Questions