DbSet doesn't have a Find method in EF7

c# entity-framework-core


I am trying to create a generic repository to access my database. In EF6 I was able to do that in order to get a specific entity:

protected IDbSet<T> dbset;

public T Get(object id)
    return this.dbset.Find(id);

DbSet in EF7 is missing a Find method. Is there a way to implement the above piece of code?

1/30/2018 12:19:19 PM

Popular Answer

Here's a very crude, incomplete, and untested implementation of .Find() as an extension method. If nothing else, it should get you pointed in the right direction.

The real implementation is tracked by #797.

static TEntity Find<TEntity>(this DbSet<TEntity> set, params object[] keyValues)
    where TEntity : class
    var context = ((IAccessor<IServiceProvider>)set).Service.GetService<DbContext>();

    var entityType = context.Model.GetEntityType(typeof(TEntity));
    var key = entityType.GetPrimaryKey();

    var entries = context.ChangeTracker.Entries<TEntity>();

    var i = 0;
    foreach (var property in key.Properties)
        var keyValue = keyValues[i];
        entries = entries.Where(e => e.Property(property.Name).CurrentValue == keyValue);

    var entry = entries.FirstOrDefault();
    if (entry != null)
        // Return the local object if it exists.
        return entry.Entity;

    // TODO: Build the real LINQ Expression
    // set.Where(x => x.Id == keyValues[0]);
    var parameter = Expression.Parameter(typeof(TEntity), "x");
    var query = set.Where((Expression<Func<TEntity, bool>>)
                Expression.Property(parameter, "Id"),

    // Look in the database
    return query.FirstOrDefault();
3/21/2016 3:53:06 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow