简体   繁体   中英

Call another method if any selected property value changed - C#

I have customer class with property. Here is my sample code

public class Customer {
public string Name {
    get;
    set;
}
public string Deparment {
    get;
    set;
}
public string AccountNo {
    get;
    set;
}

public void UpdateUserProfile(int customerId, string name, string department, string accountNo) {
    bool isNeedUpdateAccount = false;

    var customer = _context.Customers.First(c = >c.Id == customerId);

    customer.Name = name;

    if (department != customer.Deparment) {
        customer.Department = department;

        isNeedUpdateAccount = true;
    }

    if (accountNo != customer.AccountNo) {
        customer.AccountNo = accountNo;

        isNeedUpdateAccount = true;
    }

    _context.SaveChanges();

    //Check is need to update account

    if (isNeedUpdateAccount) {
        UpdateAccount(customer);
    }
}

public void UpdateAccount(Customer model) {
    // Do other business logic
}

As you see here, I need to check department and accountNo value. If value is changed then I will call another method.

Is OK if only got a few property need to check. But let say if I have more than 5 so make my code to long.

Any method can make it more simple?

If the question is not clear please let me know

The problem with your case, is that you are updating the customer in UpdateUserProfile under each if statement. To do it in a nicer way, you need to get ride of that (move to another part). and then, you can use reflection to compare both objects, but they will be checked entirely. But to do that you need to send to UpdateUserProfile a Customer

public void UpdateUserProfile(Customer newCustomer) {

    var customer = _context.Customers.First(c = >c.Id == customerId);

    var isNeedUpdateAccount = IsDifferent(customer, newCustomer)

    if(isNeedUpdateAccount){
    //TODO: Update the current Customer
     _context.SaveChanges();
    }


    if (isNeedUpdateAccount) {
        UpdateAccount(customer);
    }
}

public bool IsDifferent(Customer c1, Customer c2)
{
    foreach (PropertyInfo property in c1.GetType().GetProperties())
    {
        object value1 = property.GetValue(c1, null);
        object value2 = property.GetValue(c2, null);
        if (!value1.Equals(value2))
        {
            return true;
        }
    }
    return false;
}

in addition you can modify the method IsDifferent to return to you which properties are changed if you return a list of PropertyInfo instead of a bool.

If for any reason you don't want to compare the entire object, I reccomend you to write an extension method which compares the few properties you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM