Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have recently struggled with this same question. I'm posting this answer 2 years after the question was asked in hopes that this bit of code may help someone searching for an answer.</p> <p>I have basically implemented an extension method (as suggested by Alex James) called "Find" that operates in the same way that "Where" does, but "Find" also checks the ObjectContext to see if there are any Added entities that satisfy the given predicate. This allows you to find an entity even if it hasn't been saved to the database yet.</p> <p>Find returns an IQueryable(of T) so that you can use it just like any other LINQ operator.</p> <pre><code>&lt;Extension()&gt; Public Function Find(Of T As Class)(ByVal OSet As ObjectSet(Of T), _ ByVal predicate As Expression(Of Func(Of T, Boolean))) _ As System.Linq.IQueryable(Of T) 'Check the object context for Added objects first. Dim AddedContextObjects = OSet.Context.ObjectStateManager _ .GetObjectStateEntries(EntityState.Added) _ .Select(Function(entity) entity.Entity).OfType(Of T)() Dim Cpredicate = predicate.Compile Dim MatchingObjects As New List(Of T) For Each TObj As T In AddedContextObjects If Cpredicate.Invoke(TObj) Then MatchingObjects.Add(TObj) End If Next 'Now include a query to retrieve objects from the DB. Dim DBObjects = OSet.Where(predicate) If MatchingObjects.Count &gt; 0 Then 'We found some added objects in the context. 'We want to return these objects as well as any Objects in DB 'that satisfy the predicate. Return MatchingObjects.Union(DBObjects).AsQueryable Else 'We didn't find any added objects in the context, 'so we just return the DB query. Return DBObjects End If End Function </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