DBML:
[Function(Name="dbo.p_GetStudyStageSubjectGroup")]
public ISingleResult<STUDYSTAGE_SUBJECTGROUP__QRM> p_GetStudyStageSubjectGroup([Parameter(Name = "TimePoints", DbType = "DateTime")] System.Nullable<System.DateTime> timePoints)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), timePoints);
return ((ISingleResult<STUDYSTAGE_SUBJECTGROUP__QRM>)(result.ReturnValue));
}
后台.cs页面:
DataContextSetUp context = new DataContextSetUp();
ISingleResult<STUDYSTAGE_SUBJECTGROUP__QRM> result = context.p_GetStudyStageSubjectGroup(DateTime.Now);
this.ListView1.DataSource = result;
this.ListView1.DataBind();
运行会报错:“无法枚举查询结果多次。”
查了国外的资料发现,因为linq to sql的ISingleResult<T>输出不能被列举计算大于1次。
比如当你绑定ISingleResult<T>到一个下拉框列表,结果被枚举计算并且下拉框增加了数据;然后如果你再次绑定同样的ISingleResult<T>实例到同一个控件,它会发现它的数据源和先前的一样(通过对象引用参照),最后它就不会再一次的枚举计算该ISingleResult<T>实例。
为了解决这个问题,现有两种方法可以提供:
1、实现自己的ISingleResult<T>
public class WrapperResult<T> : ISingleResult<T>
{
#region Fields
List<T> results;
object returnValue;
#endregion
#region Constructor
public WrapperResult(ISingleResult<T> inner)
{
results = inner.ToList();
returnValue = inner.ReturnValue;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return results.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)results).GetEnumerator();
}
#endregion
#region IFunctionResult Members
public object ReturnValue
{
get { return returnValue; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
2、直接把ISingleResult<T>转换为.toList<T>()
DataContextSetUp context = new DataContextSetUp();
List<STUDYSTAGE_SUBJECTGROUP__QRM> result = context.p_GetStudyStageSubjectGroup(DateTime.Now).ToList();
this.ListView1.DataSource = result;
this.ListView1.DataBind();