Entity Framework: Re-finding objects recently added to context

前端 未结 7 707
感情败类
感情败类 2020-11-30 03:53

I am using the entity framework and I\'m having a problem with \"re-finding\" objects I just created... basically it goes like this:

string theId = \"someId         


        
7条回答
  •  时光说笑
    2020-11-30 04:15

    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.

    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.

    Find returns an IQueryable(of T) so that you can use it just like any other LINQ operator.

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

提交回复
热议问题