DbSet <tentity>,IQueryable <tentity> - OOP概念</tentity> </tentity>

时间:2013-04-30 15:23:50

标签: c# asp.net oop iqueryable dbset

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; }
}

(使用Pluralsight的代码)

来自MSDN:

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

为什么我必须专门实现IQueryable?

2 个答案:

答案 0 :(得分:1)

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

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

您应该从界面类DbSet明确设置IDepartmentDataSource

答案 1 :(得分:0)

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??

因为上面的代码不起作用,但应该。即,您应该能够将IQueryable<Department>分配给Departments属性,而不仅仅是DbSet<Department>