Closed ghost closed 14 years ago
I think, GetHashCode override can be implemented in T4 template of ActiveRecord like this: public override int GetHashCode() { if(!isNew && KeyValue() != null) { return KeyValue().GetHashCode(); }
return base.GetHashCode();
}
It essentially is. But that is going to rely on the framework's implementation of the hashing function for pretty much any key value you have, which is NOT a good thing. A better implementation would hash it against the other state of the active record and return the result. If a developer needs a good hash code implementation they're going to have to do it themselves; it would be near impossible for a T4 to be dead on every time.
I've heard a couple people complain about the hashcode implementation in the T4 templates. I've got a workaround that would allow people to easily override the implementation via partial classes and partial methods without having to extend the data models.
Here's some sample code that illustrates how to do this: public partial class Foo { public override int GetHashCode() { int? result = null; TryGetHashCode(ref result); if (result.HasValue) return result.Value; return new Random().Next(); }
If you don't create a partial class for Foo, or if your partial class doesn't provide an implementation of Foo, then execution of the default hashcode executes and the result is returned. Simply providing the partial class with the implementation will override the default implementation. You already know the benefits of using partial classes when dealing with generated code.