Entity Framework 4 overwrite Equals and GetHashCode of an own class property

Posted by Zhok on Stack Overflow See other posts from Stack Overflow or by Zhok
Published on 2010-06-11T06:50:27Z Indexed on 2010/06/11 6:52 UTC
Read the original article Hit count: 338

Hi,

I’m using Visual Studio 2010 with .NET 4 and Entity Framework 4. I’m working with POCO Classes and not the EF4 Generator. I need to overwrite the Equals() and GetHashCode() Method but that doesn’t really work. Thought it’s something everybody does but I don’t find anything about the problem Online.

When I write my own Classes and Equals Method, I use Equals() of property’s, witch need to be loaded by EF to be filled. Like this:

public class Item
{
    public virtual int Id { get; set; }
    public virtual String Name { get; set; }

    public virtual List<UserItem> UserItems { get; set; }
    public virtual ItemType ItemType { get; set; }

    public override bool Equals(object obj)
    {
        Item item = obj as Item;
        if (obj == null)
        {
            return false;
        }

        return item.Name.Equals(this.Name)
            && item.ItemType.Equals(this.ItemType);
    }

    public override int GetHashCode()
    {
        return this.Name.GetHashCode() ^ this.ItemType.GetHashCode();
    }
}

That Code doesn’t work, the problems are in Equals and GetHashCode where I try to get HashCode or Equal from “ItemType” . Every time I get a NullRefernceException if I try to get data by Linq2Entites.

A dirty way to fix it, is to capture the NullReferenceException and return false (by Equals) and return base.GetHashCode() (by GethashCode) but I hope there is a better way to fix this problem.

I’ve wrote a little test project, with SQL Script for the DB and POCO Domain, EDMX File and Console Test Main Method. You can download it here: Download

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework-4