Reputation: 523
Currently I'm doing the following to retrieve the ID of a stored object in the DB which match some fields of the entity MyObject
MyObject contract = new MyObject( some parameters );
Session.Query<MyObject>().Where( x=>x.Field1==contract.Field1 && x.Field2==contract.Field2 .... ).FirstOrDefault();
What I'm looking for would be to take profit of the fact that Equal and GetHashCode are overriden to do it like this :
Session.Query<MyObject>().Where( x=>x.Equal(contract) ).FirstOrDefault();
But this doesnt work. Is there any way for me to avoid having to type again all the fields comparison in my Where clause ? I find it ugly !
Many Thanks
Upvotes: 1
Views: 72
Reputation: 123871
The answer is pretty simple and straight forward: These are different concepts.
The Equals
and GetHashCode
are C# (application, business) way how to distinguish objects in runtime. It is an operator and calulated value ... both of them not persisted.
NHibernate does not know what should be compared on the DB level.
But what is more interesting in the snippet above is this part:
MyObject contract = new MyObject( some parameters );
The some parameters could mean two things: 1) identifier or 2) dynamic searching filters.
In the first case we should profit form the surrogated keys / id:
Session.Get<MyObject>(id);
In the second, we'll be most likely (sooner or later for sure) be provided with a changing set of values. And then we can apply them dynamically.
Finally, the case you are most likely searching for is some GetByCode or GetByName. I would say, that implementing method like this
public virtual MyObject GetByCode(string code)
{
var result = Session
.Query<MyObject>()
.Where( x => x.Code == code )
.FirstOrDefault();
return result;
}
will NOT make your code dirty. In fact, this method could be on a Data layer. So, it could have later more setings (filters by user language... etc). While the Equals
and GetHashCode
belongs to Entity (POCO if possible), and should not be so dynamic.
Upvotes: 1
Reputation: 24913
You can't use Equals method, because Linq can not translate it in sql query for your object.
Upvotes: 0