Javid
Javid

Reputation: 2945

Are entities from different contexts compatible with each other?

Let's say the following piece of code is executed:

using (var e = new MyEntities())
  CurrentUser = (from u in e.users where (...) select u).SingleOrDefault();

When the using block is over, I can only access to user fields, and that's OK.

Now in some other code, in another thread, I create another instance of MyEntities and do another query like this:

using (var e = new MyEntities())
  temp = (from u in e.users where (...some other condition...).SingleOrDefault();

Now, is it right to do the following comparison? temp==CurrentUser

I mean, we know that these two objects (temp,CurrentUser) may be referring to the same record, but what about the instances? Are they the same?

Upvotes: 1

Views: 37

Answers (1)

Alexander Derck
Alexander Derck

Reputation: 14498

Both CurrentUser and temp are references, calling temp == CurrentUser only compares those references (not the actual objects) so they will never be true. If you want to compare your entities, the best thing to do is implement IEquatable and override obect.Equals() and object.GetHashcode(). Then you can call temp.Equals(CurrentUser) and that will give the desired behavior. For example:

public class User : IEquatable<User>
{
   public int Id {get; set;}
   ...

   public bool Equals(User other)
   {
      return this.Id == other.Id;
   }

   public override bool Equals(object other)
   {
      return this.Id == (User)other.Id;
   }
   public override int GetHashcode()
   {
      return this.Id.GetHashCode();
   }
}

Note: you should always override the Equals and GetHashcode methods on object too. For example HashSet<T> uses those methods internally instead of the generic version implemented by IEquatable<T> so if you don't override them, you will get the wrong results.

Upvotes: 3

Related Questions