Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As I understand it you have an object that is not being tracked by the context and you want to use EF to query for the equivalent entity in the database. (You then want to update the database with values from the object, but that will be a seperate question.)</p> <p>You can use the Find method to get an entity from the database if you know its primary key values. The tricky bit is getting the primary key values in a generic manner. This is something we want to make easier in a future version of EF but for now I have cooked up a few extension methods to help.</p> <p>First, let's get the primary key names for a given type. This is the tricky bit. It requires dropping down to ObjectContext and using the MetadataWorkspace:</p> <pre><code> public static IEnumerable&lt;string&gt; PrimayKeysFor( this DbContext context, object entity) { Contract.Requires(context != null); Contract.Requires(entity != null); return context.PrimayKeysFor(entity.GetType()); } public static IEnumerable&lt;string&gt; PrimayKeysFor( this DbContext context, Type entityType) { Contract.Requires(context != null); Contract.Requires(entityType != null); var metadataWorkspace = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; var objectItemCollection = (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace); var ospaceTypes = metadataWorkspace.GetItems&lt;EntityType&gt;(DataSpace.OSpace); var ospaceType = ospaceTypes .FirstOrDefault(t =&gt; objectItemCollection.GetClrType(t) == entityType); if (ospaceType == null) { throw new ArgumentException( string.Format( "The type '{0}' is not mapped as an entity type.", entityType.Name), "entityType"); } return ospaceType.KeyMembers.Select(k =&gt; k.Name); } } </code></pre> <p>Now we can add an extension method that makes use of this to get the key values for a given entity (which does not have to be tracked):</p> <pre><code> public static object[] PrimayKeyValuesFor(this DbContext context, object entity) { Contract.Requires(context != null); Contract.Requires(entity != null); var entry = context.Entry(entity); return context.PrimayKeysFor(entity) .Select(k =&gt; entry.Property(k).CurrentValue) .ToArray(); } </code></pre> <p>Once we have this it's pretty easy to use Find to get the entity in the database that corresponds to a given object without knowing anything about the object. For example:</p> <pre><code>var databaseOrderLine = context.Set&lt;OrderLine&gt;().Find(context.PrimayKeyValuesFor(orderLine)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload