views:

142

answers:

1

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

A: 

You're using pure POCO classes without proxy generation. In this case lazy loading is not supported, and you will have to create repository methods to load related entities yourself. That's why your ItemType entity is null (and always will be).

If you want lazy loading, you can use the EF generator to build POCO classes that support lazy loading.

Jappie
Lazy loading works, if I remove Equals/GetHashCode or catch the NullReferenceException
Zhok