29

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?

Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80
Thiện Sinh
  • 507
  • 1
  • 4
  • 19
  • 3
    Please include code as text in a `code` section and **not** as image. – zx485 Jan 21 '18 at 05:53
  • i dont now how to add a beautiful block of code so i think the picture of it is better – Thiện Sinh Jan 21 '18 at 06:10
  • Are you looking for something similar to this https://stackoverflow.com/a/31944364/1876572 – Eldho Jan 21 '18 at 07:03
  • yeah, it works when I change return type to void, but why it not works, this is a code I get frome github, I dont know why, is there any change from entity framework. but i see it also have return type, by the way, what is it? public virtual EntityEntry Add([NotNullAttribute] TEntity entity); – Thiện Sinh Jan 21 '18 at 08:24

1 Answers1

48

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.

Community
  • 1
  • 1
Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217