因为我是 ASP.NET 网络表单和 Entity Framework 的新手,所以我正在试验一个宠物项目。
在此期间,我遇到了以下我试图理解的问题:
- 我有一个 ObjectDataSource(称为
EmployerObjectDataSource),它使用业务逻辑层 (BLL) 对象的方法来选择数据 - 该方法是GetEmployer - 在我页面的
Page_PreRender回调中,我调用方法populateFields来填充 FormView 中的字段 - 在
populateFields中,我调用EmployerObjectDataSource.Select()来获取Employer记录。 - 如果返回了任何记录,我就会用返回记录中的值填充文本框。
代码如下:
//Following Dmytro's comment, I will use Page_Load instead, however this
//does not resolve the problem
//protected void Page_PreRender(object sender, EventArgs e)
protected void Page_Load(object sender, EventArgs e)
{
_username = "Lefteris";
_version = 1;
if (!Page.IsPostBack)
{
populateFields();
}
}
private bool populateFields()
{
//IEnumerable<Employer> empl = ((IEnumerable<Employer>)EmployerObjectDataSource.Select()).ToList();
//The GetEmployer method of BLL is called here (as expected)
List<Employer> empl = (List<Employer>)EmployerObjectDataSource.Select();
System.Threading.Thread.Sleep(1000);
if (empl.Count() == 1)
{
Employer employer = empl.First();
//The GetEmployer method of BLL is called here (WHY????)
((RadTextBox)EmployerFormView.Row.FindControl("txtAme")).Text = employer.AME.ToString();
((RadTextBox)EmployerFormView.Row.FindControl("txtAfm")).Text = employer.EmplrAFM.ToString();
((RadTextBox)EmployerFormView.Row.FindControl("txtName")).Text = employer.EmplrLastName.ToString();
...
GetEmployer 如下所示:
public List<Employer> GetEmployer(string username, short version)
{
DateTime today = DateTime.Today;
List<Employer> employers = (ikaRepository.GetEmployers(username, today, version)).ToList<Employer>();
Debug.Assert(employers.Count() <= 1, "This is a logical Error - Can we have more than one active Employer records per user?");
return employers;
}
问题如下: 当我附加调试器时,我看到 BLL 的 GetEmployer 方法被调用了两次。第一次在 .Select() 上,第二次是在我尝试获取 Employer 记录的第一个字段的值时。
谢谢
请您参考如下方法:
我的英语不好,我提前道歉。
您在代码隐藏中手动将 FormView 绑定(bind)到 ObjectDataSource。因此,您在 Page Loading 阶段调用了一次 Select 方法(基于当前代码)。
您是否已在标记(ASPX 内容)中将 "EmployerObjectDataSource" 分配给 EmployerFormView 的 DataSourceID,并绑定(bind) FormView 到 Page Event Handling 阶段的 ObjectDataSource (在 Load 阶段之后),所以它调用 再次选择方法。
最好不要手动绑定(bind) DataBoundControls(如 FormView)到 DataSourceControls(如 ObjectDataSource)。相反,如果需要将一些数据传递给 BLL 以用于选择/过滤逻辑,您可以在 ObjectDataSource 标记内使用 SelectParameters。
我想这种情况就是这样发生的。我建议您也应该编写标记。
另一种情况是将一个 ObjectDataSource 绑定(bind)到多个 DataBoundControls。 在这种情况下,每个 DataBoundControls 都会在其绑定(bind)时调用 ObjectDataSource 的 Select 方法。要处理这种情况,您可以使用 ObjectDataSource 的缓存功能。
我希望这些解释会有用。
我建议您在使用 ASP.NET 数据控件之前阅读这些资源:
祝你好运!
