1 /// <summary> 2 ///Entity diff Comparator 3 /// </summary> 4 /// <param name= "source" >Source Version Entity</param> 5 /// <param name= "current" >Current Version Entity</param> 6 /// <returns>true existence change false not changed</returns> 7 protected Static BOOLDifferencecomparison<t1, t2> (T1 source, T2 current,list<string> Exclude)whereT1:mbasewhereT2:mbase8 { 9Type T1 =source. GetType ();TenType t2 =Current . GetType (); Onepropertyinfo[] Property1 =t1. GetProperties (); A //exclude primary keys and underlying fields - //list<string> exclude = new list<string> () {"Id", "Inserttime", "UpdateTime", "Deletetime", "Mark", "Vers Ion "," Code "}; - foreach(PropertyInfo Pinchproperty1) the { - stringName =P.name; - if(Exclude. Contains (name)) {Continue; } - stringvalue1 = P.getvalue (source,NULL)?. ToString (); + stringvalue2 = t2. GetProperty (name)?. GetValue (Current,NULL)?. ToString (); - if(value1! =value2) + { A return true; at } - } - return false; - } - /// <summary> - ///sets the diff comparer to compare the values of two entity collections in /// </summary> - /// <param name= "source" >Source version Entity collection</param> to /// <param name= "current" >Current version Entity collection</param> + /// <returns>true existence change false not changed</returns> - protected Static BOOLDifferencecomparison<t1, t2> (list<t1> source, list<t2> current)whereT1:mbasewhereT2:mbase the { * if(source. Count! = Current. Count) {return true; } $ for(inti =0; I < source. Count; i++)Panax Notoginseng { - BOOLFlag =Differencecomparison (Source[i], current[i]); the if(flag) {returnFlag;} + } A return false; the } + /// <summary> - ///dynamically assigns the value of entity 2 to entity 1 (the name of the property is assigned) $ /// </summary> $ /// <param name= "Model1" >entity 1</param> - /// <param name= "Model2" >Entity 2</param> - /// <returns>Model1 after assignment</returns> the protected StaticT1 bindmodelvalue<t1, t2> (T1 model1, T2 Model2)whereT1:class whereT2:class - {WuyiType T1 =Model1. GetType (); theType t2 =Model2. GetType (); -propertyinfo[] Property2 =T2. GetProperties (); Wu //Exclude PRIMARY Key -list<string> exclude =Newlist<string> () {"Id" }; About foreach(PropertyInfo Pinchproperty2) $ { - if(Exclude. Contains (P.name)) {Continue; } -T1. GetProperty (p.name)?. SetValue (Model1, P.getvalue (Model2,NULL)); - } A returnModel1; +}
List<string> exclude is used to exclude fields from entities that will not participate in the comparison
Transferred from: https://www.cnblogs.com/codelir/p/6856194.html
C # Entity/Collection Difference comparison, compare two entities or collection values, dynamically assign the value of entity 2 to entity 1 (the name of the property to assign value)