Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is IDbSet<T> in entity core

enter image description here

public abstract class RepositoryBase<T> : IRepository<T> where T : class
{
    private ShopCoreDbContext dbContext;
    private readonly DbSet<T> dbSet; //here
    protected IDbFactory DbFactory { get; private set; }
    protected ShopCoreDbContext DbContext
    {
        get => dbContext ?? (dbContext = DbFactory.Init());
    }
    protected RepositoryBase(IDbFactory dbFactory)
    {
        DbFactory = dbFactory;
        dbSet = DbContext.Set<T>();
    }
    public virtual T Add(T entity)
    {
        return dbSet.Add(entity); //err here
    } 
}

With IDbSet nothing happen. But IDbSet interface no longer exists in entity core. This is error detail:

cannot implicitly convert type Microsoft.entityframeworkcore.changetracking.entityentry to T

It requires it must be an interface.
So what should I do now?

like image 885
Thiện Sinh Avatar asked Jan 21 '18 05:01

Thiện Sinh


People also ask

What is IDbSet?

An IDbSet<TEntity> represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet<TEntity> is a concrete implementation of IDbSet.

What is DbSet in EF core?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.


1 Answers

To solve your immediate problem:

The Add method doesn't return the entity directly, but a wrapper entity. Use its .Entity property to get back the value (or return the passed in value):

    public virtual T Add(T entity)
    {
        return dbSet.Add(entity).Entity; 
    }

About the IDbSet<T> interface: Entity Framework Core does not have an IDbSet<T> interface.

According to this GitHub issue there is no plan to bring it back since DbSet<T> is now an abstract base class that can be used to mock for testing or subclassed:

The issue with interfaces is we either exclude new members or break folks who implement the interface. The base class is also slightly better for folks writing their own test doubles (rather than using a mocking framework) since you only need to implement the methods you actually use.

[…]

Closing as we have been using the base type approach in EF6.x for a few releases now and have not heard any feedback on real scenarios where this doesn't work as well.

like image 139
Martin Ullrich Avatar answered Oct 19 '22 12:10

Martin Ullrich