I am attempting to add some multi-threading to a WPF application I have created in order to create a more responsive interface, but as Linq-to-SQL data contexts are not thread safe, I am forced to use one per thread.
My problem is that the same entity pulled from two different contexts, are apparently not equal. Take the following code sample, where I have a simple database with employee records:
var context1 = new DataModelDataContext();
var context2 = new DataModelDataContext();
var emp1 = context1.Employees.Single(x => x.ID == 1);
var emp2 = context2.Employees.Single(x => x.ID == 1);
Console.WriteLine(string.Format("Employees equal: {0}", emp1 == emp2));
Console.ReadKey();
When run, this returns:
Employees equal: False
In my mind I would expect these to objects to be equal, as they would be if I pulled them from the same context. I can overcome this by checking emp1.ID == emp2.ID instead, but this is problematic when trying to use WPF bindings such as SelectedItem.
Is there any way around this? This behaviour appears to be the same in Entity Framework as well.
Two independently instantiated objects may represent the same item in the data store, but they will never evaluate as equal in any language. You will have to write code that compares the members of each object to determine if their data is equal. This may or may not be as simple as comparing the primary key.
You can always override Equals and GetHasCode to ensure that objects are "equal" even if they are not same instance (which is default equality rule used for reference types).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With