简体   繁体   中英

DbSet<TEntity>, IQueryable<TEntity> - OOP concepts

public interface IDepartmentDataSource
{
    IQueryable<Department> Departments { get; }
}

public class DepartmentDb : DbContext, IDepartmentDataSource 
{
    //Error: property cannot implement property.... 
    public DbSet<Department> Departments { get; set; } 


    //should be: 
    //public IQueryable<Department> Departments { get; set; }
}

(Used code from Pluralsight)

From MSDN:

public class DbSet<TEntity> : DbQuery<TEntity>, 
IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, 
IQueryable, IEnumerable 
where TEntity : class

Why do I have to specifically implement as IQueryable ?

public class DepartmentDb : DbContext, IDepartmentDataSource
{
    public DbSet<Department> Departments { get; set; }

    IQueryable<Department> IDepartmentDataSource.Departments
    {
        get { return Departments; }
    }
}

You should explicitly set your DbSet from the interface class IDepartmentDataSource .

public class DepartmentDb : DbContext, IDepartmentDataSource 
{
    //Error: property cannot implement property.... 
    public DbSet<Department> Departments { get; set; } 
}

public class MyQueryable<T> : IQueryable<T> {}

....

MyDepartmentDb.Departments = new MyQueryable<Department>(); // Error!
// but it implements IDepartmentDataSource
// which should let any IQueryable<Department> in, so what gives??

Because the code above wouldn't work, but should. ie you should be able to assign any IQueryable<Department> to the Departments property, not just a DbSet<Department> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM