We want to have GetById()
and GetAll()
methods at least, as these methods are used frequently.
The simplest get method that we will code is the GetById()
method, which is not just cleverly named, but should also retrieve an object by its ID. This method is really simple to code, because NHibernate already knows how to go get an object using its unique identifier.
To retrieve a record by its ID, all we have to do is call Session.Get<T>()
and pass it an ID.
Note
If you haven't seen the <T>
syntax before (or the (Of T)
syntax in VB.NET), it is the .NET syntax for generics
. It simply means ANY TYPE, so <T>
for our Contact
object would be <Contact>
or (Of Contact)
.
An example of the GetById()
method would look as follows:
public Contact GetById(int Id) { return Session.Get<Contact>(Id); }
The VB.NET code looks very similar, we just substitute the (Of T)
syntax for the <T>
syntax of C#:
Public Function GetById(ByVal Id As Integer) As Contact...