继承类方法的可见性没有意义?

时间:2015-03-05 01:25:14

标签: c# entity-framework inheritance repository-pattern unit-of-work

以下代码代表我在工作单位的努力。

接口

public interface IUnitOfWork
{
    IFieldRepository FieldRepository { get; }
    void Save();
}

public interface IFieldRepository
{
    IEnumerable<Field> GetAllFields( int page, int amount, string sortByKey, SortDirection sortDirection );
}

具体的工作单位:

public class EFUnitOfWork : IDisposable, IUnitOfWork
{
    private EFDbContext context = new EFDbContext();

    private IFieldRepository fieldRepository;

    public IFieldRepository FieldRepository
    {
        get
        {

            if( this.fieldRepository == null )
            {
                this.fieldRepository = new EFFieldRepository( context );
                // At this point i can see this.fieldRepository.Insert() absolutely fine
            }
            return fieldRepository;
        }
    }

    // ...

具体字段存储库:

public class EFFieldRepository : EFGenericRepository<Field>, IFieldRepository
{
    public EFFieldRepository( EFDbContext context )
        : base( context )
    {}

    // ...

具体的通用存储库:

public class EFGenericRepository<TEntity> where TEntity : class
{
    internal protected EFDbContext context;
    internal protected DbSet<TEntity> dbSet;

    public EFGenericRepository( EFDbContext context )
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual void Insert( TEntity entity )
    {
        dbSet.Add( entity );
    }

    // ...

控制器类:

public class FieldController : Controller
{
    IUnitOfWork unitOfWork;

    public FieldController( IUnitOfWork unitOfWork )
    {
        this.unitOfWork = unitOfWork;
    }

    // GET: Field
    public ActionResult List()
    {
        unitOfWork.FieldRepository.Insert( ... ); // This method isn't visible? But GetAllFields is visible
        return View();
    }
}

问题来自我的控制器内部,我无法访问应该从EFFieldRepository继承的方法?

如果您查看EFUnitOfWork.FieldRepository内的评论,我可以在那时看到它们

什么阻止继承类显示其方法?

1 个答案:

答案 0 :(得分:2)

unitOfWork.FieldRepository的类型为IFieldRepository,因此只有GetAllFields()可见:

IFieldRepository repository = unitOfWork.FieldRepository;
repository.GetAllFields();

您需要将其投放到EFGenericRepository<Field>, IFieldRepository不要这样做!)或将此方法添加到界面:

public interface IFieldRepository
{
    void Insert(Field entity);
}

由于virtual在这里没有任何区别,您可以将其删除。


但我的所有存储库都有一个通用接口:

public interface IRepository<T>
{
    IEnumerable<T> GetAll(int page, int amount, string sortByKey, SortDirection sortDirection);
}
修改

或更好的版本以使用EF:

public interface IRepository<T>
{
    IEnumerable<T> GetAll();

    IEnumerable<T> GetAll(int page, int amount, Expression<Func<IQueryable<T>, Func<T, object>, IEnumerable<T>>> sort);
}

用法:

repository.GetAll(x, y, (seq, p) => seq.OrderBy(p => p.Name));