Windows窗体控件的问题绑定实体框架5对象

问题描述:

我在Windows窗体应用程序(vs2010,.net 4)中首次使用实体框架(数据库优先,实体框架5)。我遇到了我的实体对象和windows窗体控件之间的绑定问题。我有文本框,datetimepicker和组合框控件。当我用绑定的控件打开窗口时,正确的数据显示在控件中。但是,当我更改其中一个控件的值并将控件关闭时,该值将恢复为控件中的原始值,就好像该值未被推送到对象一样。下面是代码exerpts:Windows窗体控件的问题绑定实体框架5对象

我的实体对象:

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 < PropertyName>更改为早期版本的实体框架创建的方法。我一直试图陷入错误,当焦点离开控制,但认为这不可能是最好的方法:

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; 
     } 

任何帮助,将不胜感激。谢谢!

事实证明,除非在绑定中指定了“formattingEnabled”,否则当绑定将非空值赋予对象的可空属性时会收到异常。

所以,像这样结合的工作原理:

this.dateDocument.DataBindings.Add(new Binding("Value", this.document, "DocumentDate", true)); 

,而这并不:

this.dateDocument.DataBindings.Add(new Binding("Value", this.document, "DocumentDate")); 

我还不清楚我怎么会陷由于绑定类型的错误简单地捕获错误并用原始值替换控件中的值。