0

I have one online database on wcf and one offline database. I want to synchronize those so I started with mapping the online data into an object of offline data.

List<com.somee.wobservice.Customer> onlineCus = myservice.QueryCustomer();
List<Customer> offlineCus = dbc.Customers.ToList();
List<Customer> onlineCusMap = new List<Customer>();

foreach (com.somee.wobservice.Customer c in onlineCus)
{
     Customer cus = new Customer();
     cus.customer_id = c.customer_id;
     cus.customer_name = c.customer_name;
     cus.customer_email = c.customer_email;
     cus.password = c.password;
     cus.balance = c.balance;

     onlineCusMap.Add(cus);
 }

Now, I have 2 objects of the class Customer (a table in my database). But when I compared to get the except from them, it returned all data of the offline database (suppose to be no data because the data in those objects are same)

List<Customer> toInsert = offlineCus.Except(onlineCusMap).ToList();

Any suggestion to compare those 2 objects?

2
  • 5
    Does your Customer class override Equals and GetHashCode? If not, that's why it's not finding any duplicates. Commented Jun 7, 2014 at 8:20
  • Try implementing IEquatable<customer> suggested by the msdn docs. Which overrides the above methods. Not sure if this is required though. Commented Jun 7, 2014 at 8:24

1 Answer 1

1

As Jon pointed out in the comment in order to use Except you would need to override Equals/GetHashCode in order to determine what distinguishes a customer; By default your comparator will be by reference which in most cases will not suffice.

An alternative to that would be to just query for any customers which do not exist in the onlineCusMap list. I think it's probably safe to assume that customer_id is going to be unique enough to distinguish a customer

List<Customer> toInsert = 
    offlineCus.Where(x => !onlineCusMap.Any(y => y.customer_id == x.customer_id))
              .ToList();

If you do decide to override Equals I suggest you read the guidelines on how to do so correctly because it's not quite as simple as it may seem.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, your linq statement looks more lovely than Equals example. Thanks a lot!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.