I have an object called Market in my C# 4 application:
public class Market : BusinessBase
{
public Market()
{
}
public virtual int Id { get; set; }
public virtual string Symbol { get; set; }
public virtual string Description { get; set; }
}
I have a table called markets in SQL Server:
CREATE TABLE [dbo].[markets](
[marketId] [int] IDENTITY(1,1) NOT NULL,
[symbol] [varchar](10) NOT NULL,
[description] [varchar](30) NOT NULL,
[version] [int] NOT NULL,
CONSTRAINT [PK_markets] PRIMARY KEY CLUSTERED
([marketId] ASC)
GO
CREATE UNIQUE NONCLUSTERED INDEX [NIDX_markets_symbol] ON [dbo].[markets] ([symbol] ASC)
GO
My mapping file looks like this:
<class name="MooDB.BusinessLayer.Market" table="markets">
<id name="Id" column="marketId" type="Int32">
<generator class="native" />
</id>
<version name="Version" column="version" type="integer" unsaved-value="0" />
<property name="Symbol" column="symbol" type="string" length="10" />
<property name="Description" column="description" type="string" length="30" not-null="true" />
</class>
I can retrieve a market from the database by Id by simply using this method:
public Market GetMarketById(int marketId)
{
ISession session = GetSession();
return session.Get<Market>(marketId);
}
I want to do the same thing but pass in the Symbol instead. Symbol is enforced unique in the database and I want to return a Market object. I am trying this code:
public Market GetMarketBySymbol(string symbol)
{
ISession session = GetSession();
return session.Get<Market>(symbol);
}
I know this is wrong but is there a way to return one object which maps to one unique row in the database but not retrieve it by PK? I could simply get an <IList>of Market objects and then just return the one using a ‘foreach’ but that feels inelegant to me.
If you are using NH 3+ you can use LINQ:
Or QueryOver: