在下面的QueryableEntities方法中,
IEnumerable<Competition>.AsQueryable()
将返回无法返回的IQueryable<Competition>
,因为它期待IQueryable<T>
我只能写一种方法来返回IQueryable<Competition>
和IQueryable<Submission>
如果有人知道怎么做,请告诉我,谢谢
public partial class WinBoutsDataContext<T> : System.Data.Linq.DataContext where T : class
{
public IQueryable<T> QueryableEntities
{
get
{
if (typeof(T).Equals(typeof(Model.Competition)))
{
return this.ConvertToCompetitionList(
this.GetTable<Storage.Competition>()).AsQueryable();
}
else if(typeof(T).Equals(typeof(Model.Submission)))
{
return this.ConvertToSubmissionList(
this.GetTable<Storage.CompetitionEntry>()).AsQueryable();
}
}
}
public DataAccess.Model.Competition ConvertToCompetition(DataAccess.Storage.Competition comp)
{
DataAccess.Model.Competition modelComp = new DataAccess.Model.Competition
{
CompetitionID = comp.CompetitionID,
Active = comp.Active,
CompetitionStatusID =
comp.CompetitionStatusID,
Duration = comp.Duration,
EndDate = comp.EndDate,
Entrants = comp.Entrants,
Featured = comp.Featured,
Image = comp.Image,
IsOvertime = comp.IsOvertime,
MaxEntrants = comp.MaxEntrants,
Notes = comp.Notes,
OvertimeDuration = comp.OvertimeDuration,
OvertimeEnd = comp.OvertimeEnd,
OvertimeStart = comp.OvertimeStart,
ParentCompetitionID = comp.ParentCompetitionID,
Prize = comp.Prize, StartDate = comp.StartDate,
SuggestedBy = comp.SuggestedBy,
Summary = comp.Summary,
Title = comp.Title
};
return modelComp;
}
public IEnumerable<DataAccess.Model.Competition> ConvertToCompetitionList(IEnumerable<DataAccess.Storage.Competition> compList)
{
List<DataAccess.Model.Competition> compModelList = new List<DataAccess.Model.Competition>();
foreach (DataAccess.Storage.Competition comp in compList)
{
compModelList.Add(ConvertToCompetition(comp));
}
return compModelList;
}
}
答案 0 :(得分:2)
同意Adrian对设计原则的评论,但是如果你想这样做的话
public IQueryable<T> QueryableEntities
{
get
{
if (typeof(T).Equals(typeof(Model.Competition)))
{
return this.ConvertToCompetitionList(
this.GetTable<Storage.Competition>()).AsQueryable() as IQueryable<T>;
}
else if(typeof(T).Equals(typeof(Model.Submission)))
{
return this.ConvertToSubmissionList(
this.GetTable<Storage.CompetitionEntry>()).AsQueryable() as IQueryable<T>;
}
}
}
将编译并运行正常。 x as IQueryable<T>
如果可以投放x
,则IQueryable<T>
投放到null
,如果不投,则Model.Competition
投放IQueryable<Model.Competition>
。
注意:这意味着当您构建通用类时,如果它具有类型Model.Submission
,它将返回IQueryable<Model.Submission>
,如果它具有类型null
,它将返回{{1}},并将为任何其他类型返回{{1}}。
答案 1 :(得分:0)
通常最好不要概括。很多开发人员似乎花了很多时间试图让一个属性/方法/类做很多事情,但它违背了许多面向对象的原则。就个人而言,我只会使用2个属性,可能称为Competitions
,另一个Submissions
。与QueryableEntities
相比,它的意图要多得多。