开发者

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

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 override the Equals() and GetHashCode() methods, but that doesn’t really work. I 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, which need to be loaded by EF to be fill开发者_JS百科ed. 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 written 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜