I have the following property on a class persisted with NHibernate:
public virtual string Code { get { return Id.ToString("SP000"); } }
However I’ve come to do this, which of course doesn’t work:
Session.Linq<MyType>().Where(x => x.Code.Contains(searchTerm));
So, is it possible to store Code in the database and have NHibernate manage the
.ToString("SP000")
to set Code, when ID is set?
Edit: I guess I need an interceptor, but I’m not sure how to implement what I need.
Let me restate the question to make sure I understand it: You have an integer primary key mapped to the Id property but you want to query on the Code property that is a read-only string. If you had records with code ‘SP123’ and ‘SP234’, the query would return both records for the searchTerm ‘2’.
Try using HQL (Hibernate Query Language) instead of Linq for this query. You can use SQL functions in HQL, so your query would look something like:
You’ll want to rewrite that to use a parameter so that it’s not vulnerable to SQL injection attack.