遇到存储库模式与使用抽象类相结合的问题。存储库模式和抽象类的问题
我有一个存储库,它实现了一个方法返回一个抽象类型的ICollection。
这里是我的抽象类:
public abstract class Location
{
public abstract string Name { get; set; }
public abstract LocationType Type { get; }
}
这里有一个具体实现该抽象类:
public class Country : Location
{
public override string Name { get; set; }
public override LocationType Type { get { return LocationType.Country; } }
}
这里是我的库:
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 };
}
}
目前为止都是很好的。
现在服务:
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>();
}
}
有问题。我试图从存储库中返回一个具体类型列表(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语法的一种情况吗?或者是我的设计模式完全错误?
+1这完全是最好的解决方案。 – 2010-07-30 03:55:17
太棒了,所以这是一个LINQ问题,而不是抽象/存储库问题。谢谢!! – RPM1984 2010-07-30 04:04:00