dimanche 8 janvier 2023

Iterate model inside model and detect changes

I'm working on an Angular (front-end) C# (back-end) application. This application uses Entity Framework code first.

So I want to evaluate two models to compare two models and look for their differences. After some investigation, I found that it can be achieved using Reflection. So I have the following code:

public static List<Variance> Compare<T>(this T val1, T val2)
            {
                var variances = new List<Variance>();
                var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var property in properties)
                {
               
                var v = new Variance
                    {
                        PropertyName = property.Name,
                        valA = property.GetValue(val1),
                        valB = property.GetValue(val2)
                    };

                if (v.valA == null && v.valB == null)
                    {
                        continue;
                    }
              
                    if (
                        (v.valA == null && v.valB != null)
                        ||
                        (v.valA != null && v.valB == null)
                    )
                    {
                    if(v.valA != null)
                    {
                        if (v.valA.ToString() == "0" && v.valB == null)
                        {
                            continue;
                        }
                    }
                   

                    if(v.valA == null && v.valB != null)
                    {
                        continue;
                    }

                    variances.Add(v);
                        continue;
                    }
                

                if (!v.valA.Equals(v.valB))
                    {
                        variances.Add(v);
                    }
                }
                return variances;
            }
    }

    public class Variance
    {
        public string PropertyName { get; set; }
        public object valA { get; set; }
        public object valB { get; set; }
    }

It is working, but only for root model and not their models inside the model. I.E, I'm comparing this model:

 public partial class Profile : BaseAuditModel
    {

        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public virtual ICollection<EmploymentHistory> EmploymentHistories { get; set; }
    }

The EmploymentHistories detects it has differences, but in reality, they do not have any difference; I think it is marked as a difference because the method does not know what is inside it, so my question is. How can I detect if it is a collection? and when it is a collection iterate and detect the changes as the root one

enter image description here enter image description here





Aucun commentaire:

Enregistrer un commentaire