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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With