tags:

views:

277

answers:

1

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. Any help appreciated

Thanks

Andrew

+1  A: 

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:

"from Table t where 'SP' + CAST(Id AS varchar) LIKE '%" + searchTerm + "%'";

You'll want to rewrite that to use a parameter so that it's not vulnerable to SQL injection attack.

Jamie Ide
Thanks for the suggestion however I cant use HQL because I have abstraction patterns encapsulating the ISession behind an IQueryable interface so I must use Linq. I also don't want magic strings (the HQL) floating about. I dont mind having Code in the db, im not trying to avoid it, just implement it
Andrew Bullock
OK. Create a view that contains the code column and map it as a read-only property in your object by mapping the view instead of the table.
Jamie Ide