Entity Framework: Re-finding objects recently added to context

前端 未结 7 703
感情败类
感情败类 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:10

    The extension method bellow is to DbSet<>

    public static T TryAttach(this DbSet dbSet, T entity, Expression> predicate) where T : class
    {
         T found = dbSet.Local.SingleOrDefault(predicate.Compile());
         if (found == null) dbSet.Attach(entity);
         return found ?? entity;
    }
    

    How to use:

    contextInstance.MyEntity.TryAttach(entityInstance, e => e.ID == entityInstance.ID);
    

    btw: I love generics!

提交回复
热议问题