Back in EF 4 it was not possible. Is it possible to use interfaces with a DbSet
in EF6 or EF Core?
public class LfSp3Ctx : DbContext, ILfSp3Ctx
{
public DbSet<ILfSp3Project> ProjectSE { get; set; }
}
The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views. Adds the given entity to the context with the Added state.
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.
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.
A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.
It is possible, but it requires some trickery. EF will only instantiate DbSet types directly. Thus, you'd have to create your own interface that wraps/exposes all the DbSet methods you want and the actual implementation takes the DbSet instance in its constructor. Then on the DbContext class, you have to do something like this:
IDbSet<DigimonEntity> DigimonRepository => new DbSetRepository<DigimonEntity>(this.Digimons);
DbSet<DigimonEntity> Digimons { get; set; }
public class DbSetRepository<T> : IDbSet<T> where T : class
{
private readonly DbSet<T> _set;
public DbSetRepository(DbSet<T> set) => _set = set;
public Type ElementType => ((IQueryable<T>)_set).ElementType;
public Expression Expression => ((IQueryable<T>)_set).Expression;
public IQueryProvider Provider => ((IQueryable<T>)_set).Provider;
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)_set).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)_set).GetEnumerator();
void IDataStoreRepositoryWrite<T>.Add(T entity) => _set.Add(entity);
void IDataStoreRepositoryWrite<T>.Update(T entity) => _set.Update(entity);
void IDataStoreRepositoryWrite<T>.Delete(T entity) => _set.Remove(entity);
Task IDataStoreRepositoryWrite<T>.AddAsync(T entity, CancellationToken token) => _set.AddAsync(entity, token);
}
Something like this. Mine is kind of specific to the implementation I was trying to pull off at the time. :)
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