【发布时间】:2026-02-02 12:55:01
【问题描述】:
我第一次在 Windows 窗体应用程序(vs2010,.net 4)中使用实体框架(数据库优先,实体框架 5)。我的实体对象和 Windows 窗体控件之间的绑定有问题。我有文本框、日期时间选择器和组合框控件。当我打开一个带有绑定控件的窗口时,控件中会显示正确的数据。但是,当我更改其中一个控件中的值并关闭控件时,该值将恢复为控件中的原始值,就好像该值没有被推送到对象一样。以下是代码摘录:
我的实体对象:
namespace Entities
{
using System;
using System.Collections.Generic;
public partial class ExternalDocument
{
public int ExternalDocumentID { get; set; }
public bool Active { get; set; }
public bool Closed { get; set; }
public Nullable<int> CompanyID { get; set; }
public Nullable<int> ContactID { get; set; }
public string DocumentNbr { get; set; }
public Nullable<System.DateTime> DocumentDate { get; set; }
public Nullable<System.DateTime> DateReceived { get; set; }
public virtual Company Company { get; set; }
public virtual Contact Contact { get; set; }
}
}
数据绑定:
private void SetDataBindings()
{
LoadComboBoxValues();
this.textDocumentNbr.DataBindings.Add("Text", this.document, "DocumentNbr");
this.textDocumentNbr.Leave += new EventHandler(textDocumentNbr_Leave);
this.dateDocument.DataBindings.Add(new Binding("Value", this.document, "DocumentDate"));
this.dateReceived.DataBindings.Add("Value", this.document, "DateReceived");
this.comboCompanyID.DataBindings.Add("SelectedValue", document, "CompanyID");
}
我想知道设置对象属性时是否存在实体框架错误,但我无法找到捕获此类错误的好方法。我的实体框架对象没有为早期版本的实体框架创建的 On
private void dateDocument_Leave(object sender, EventArgs e)
{
string errorString = this.entitiesController.GetValidationErrors();
this.errorDocumentDate.SetError(this.dateDocument, errorString);
}
public string GetValidationErrors()
{
string errorString = "";
List<DbEntityValidationResult> errorList = (List<DbEntityValidationResult>)this.finesse2Context.GetValidationErrors();
if (errorList.Count > 0)
{
foreach(var eve in errorList)
{
errorString += "Entity of type " + eve.Entry.Entity.GetType().Name + " in state" + eve.Entry.State + " has the following validation errors:"; ;
foreach (var ve in eve.ValidationErrors)
{
errorString += "- Property: " + ve.PropertyName + " Error: " + ve.ErrorMessage;
}
}
}
return errorString;
}
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: winforms data-binding entity-framework-5