Entity Framework 4 overwrites Equals and GetHashCode of class native property

Im using Visual Studio 2010 with .NET 4 and Entity Framework 4. Im works with POCO classes, not with the EF4 generator. I need to override the Equals() and GetHashCode() methods, but that really doesn't work. I thought this was doing something, but I did not find anything about the problem on the Internet.

When I write my own classes and the Equals method, I use the Equals() properties that EF needs to load to fill. 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(); } } 

This code does not work. The problems are in Equals and GetHashCode , where I am trying to get a HashCode or Equal from ItemType . Every time I try to get Linq2Entites data, I get a NullRefernceException.

The wrong way to fix this is to catch a NullReferenceException and return false (by Equals) and return base.GetHashCode() (via GetHashCode ), but I hope there is a better way to fix this problem.

I wrote a small test project with SQL Script for the POCO database and domain, the main method for testing EDMX files and consoles. You can download it here: Download

+4
source share
1 answer

You use pure POCO classes without generating proxies. In this case, lazy loading is not supported, and you will have to create repository methods to load related objects yourself. Therefore, your ItemType is null (and always will be).

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

0
source

Source: https://habr.com/ru/post/1312526/


All Articles