Search code examples
c#entity-frameworkpartial-methods

How do I modify values of my object in partial class of EntityDataModel


I have a EntityDataModel generated from my database (Visual Studio 2010, asp.net 4.0, c#). I am trying to use a partial class associated to an entity class to perform some business logic (in this case check a phone number field and remove spaces).

If I use something like that:

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

then I end up getting an infinite loop (because my FormatPhoneNumber method modifies MobilePHoneNo which raises the event again etc) and then I get... a stack overflow!

When I try using the OnMobilePhoneNoChanging instead, and modify the MobilePHoneNo property (or the value value) then the value is not saved properly.

What should I do ?


Solution

  • Have a look in your model's .Designer.cs file. You'll see something like this:

        /// <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.