Where is IDbSet in entity core

.net-core c# entity-framework-core

Question

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?

1
17
1/21/2018 8:35:34 AM

Accepted Answer

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.

30
1/21/2018 9:23:54 AM


Related Questions





Related

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