2

我有一个从我的数据库(Visual Studio 2010、asp.net 4.0、c#)生成的 EntityDataModel。我正在尝试使用与实体类关联的部分类来执行一些业务逻辑(在这种情况下,检查电话号码字段并删除空格)。

如果我使用类似的东西:

 partial void OnMobilePhoneNoChanged()  
    {  
        if (MobilePhoneNo != null)  
        {  
            MobilePhoneNo = ATG_COModel_Common.FormatPhoneNumber(MobilePhoneNo);  
        }  
    }  

然后我最终得到一个无限循环(因为我的 FormatPhoneNumber 方法修改了 MobilePHoneNo 再次引发事件等),然后我得到......堆栈溢出!

当我尝试改用 OnMobilePhoneNoChanging 并修改 MobilePHoneNo 属性(或value值)时,该值未正确保存。

我该怎么办 ?

4

1 回答 1

2

查看您的模型.Designer.cs文件。你会看到这样的东西:

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.String MobilePhoneNo 
    {
        get
        {
            return _MobilePhoneNo;
        }
        set
        {
            OnMobilePhoneNoChanging(value);
            ReportPropertyChanging("MobilePhoneNo");
            _MobilePhoneNo = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("MobilePhoneNo");
            OnMobilePhoneNoChanged();
        }
    }
    private global::System.String _MobilePhoneNo;
    partial void OnMobilePhoneNoChanging(global::System.String value);
    partial void OnMobilePhoneNoChanged();

Notice that as well as the partial Changing and Changed methods you already know about, there's a backing field. Because your code is in a partial piece of the class, you have access to all members, including the private ones. So you can implement the partial Changed method, and directly alter _MobilePhoneNo:

partial void OnMobilePhoneNoChanged()  
{  
    if (_MobilePhoneNo != null)  
    {  
        _MobilePhoneNo = ATG_COModel_Common.FormatPhoneNumber(_MobilePhoneNo);  
    }  
}  

which is what you want.

于 2012-06-21T08:49:21.737 回答