存储库模式和抽象类的问题

RPM*_*984 3 .net linq abstract-class icollection repository-pattern

遇到存储库模式的问题以及抽象类的使用.

我有一个存储库,它实现了一个返回抽象类型的ICollection的方法.

这是我的抽象类:

public abstract class Location
{
   public abstract string Name { get; set; }
   public abstract LocationType Type { get; }
}
Run Code Online (Sandbox Code Playgroud)

这是抽象类的具体实现:

public class Country : Location
{
   public override string Name { get; set; }
   public override LocationType Type { get { return LocationType.Country; } }
}
Run Code Online (Sandbox Code Playgroud)

这是我的存储库:

public class LocationsRepository : Locations.Repository.ILocationsRepository
{
   public ICollection<Location> GetAllLocations()
   {
      Country america = new Country { Name = "United States" };
      Country australia = new Country { Name = "Australia" };
      State california = new State { Name = "California", Country = america };

      return new List<Location>() { america, australia, california };
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止都很好.

现在的服务:

public class CountryService : ICountryService
{
   private ILocationsRepository repository;

   public CountryService()
   {
      // in reality this is done by DI, but made 'greedy' for simplicity.
      this.repository = new LocationsRepository();
   }

   public List<Country> GetAllCountries()
   {
      // errors thrown by compiler
      return repository.GetAllLocations()
                       .Where(l => l.Type == LocationType.Country)
                       .ToList<Country>();
   }
}
Run Code Online (Sandbox Code Playgroud)

有问题.我正在尝试Country从存储库返回一个具体类型()的列表,该存储库返回ICollection<T>一个抽象类型.

得到2个编译时错误:

'System.Collections.Generic.IEnumerable'不包含'ToList'的定义和最佳扩展方法重载'System.Linq.ParallelEnumerable.ToList(System.Linq.ParallelQuery)'有一些无效的参数

实例参数:无法从'System.Collections.Generic.IEnumerable'转换为'System.Linq.ParallelQuery'

那么,我该如何实现这种模式呢?

我可以理解这个问题(你不能实例化一个抽象类型),那么Enumerator(.ToList)是否会尝试实例化它,因此错误?

万一你不明白我想做什么:

  • 我希望我的存储库返回ICollection<T>一个抽象类型
  • 我希望我的服务(我将为每个具体类型都有一个)来返回基于该单一存储库方法的具体类型列表

这只是LINQ语法的一个例子吗?或者我的设计模式完全错了?

Nec*_*ros 7

repository.GetAllLocations().OfType<Country>().ToList();
Run Code Online (Sandbox Code Playgroud)

你甚至不需要LocationType枚举