如何在EntityDataModel的部分类中修改我的对象的值

时间:2012-06-21 08:23:53

标签: c# entity-framework partial-methods

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

如果我使用类似的东西:

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

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

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

我该怎么办?

1 个答案:

答案 0 :(得分: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();

请注意,除了您已了解的部分ChangingChanged方法,还有一个支持字段。由于您的代码属于的部分内容,因此您可以访问所有成员,包括私有成员。因此,您可以实现部分Changed方法,并直接更改_MobilePhoneNo

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

这就是你想要的。