Skip to content

Going through IDictionary in a class NHibernate

October 15, 2012

As stated, I wanted to write a query method to go through all the records in an IDictionary collection inside a class in NHibernate, it was however not as easy as I had expected to be.

Initially what I had done was create a class representing the IDictionary which there was already a table for this,and created the properties for this class. It compiled ok, but when it came to getting all the records, using ICriteria, it didn’t return anything and instead threw a Object reference not set to an instance of an object. I had thought that a mapping field or property in the class had been missing which was right, one field was missing, but adding this in still didn’t solve the problem.

I later found out that you CANNOT run a query for a table with NO PRIMARY KEY in NHibernate, every table needs a primary key if you want to run a query for that table, otherwise it has to be a relation off a class.

Ah ok!

So this means that I had to do this the long way and traverse through each of the class objects holding the IDictionary, its the only way logically to do this without tampering out NHibernate’s keywords.

E.g.

public class Customer

{

public virtual IDictionary<short, string> Banks

{

get { return _Banks; }

set { _Banks = value; }

}

private IDictionary<short, string> _banks = new Dictionary<short, string>();

}

So if you think of a scenario where a customer needs to have bank accounts in several Banks, this can be a relation as described by the IDictionary. (mapped jusing the map tag of IDictionary).

To go through the whole listy of all the customer’s banks (needed to do a similar scenario but not banks!), you need to traverse through all customers.

IList<Customer> allCustomers = Customer.GetAllCustomers();

foreach (Customer customer in allCustomers)

{

IDictionary<short, string> customerBank = customer.Banks;

var flattenedKeys = customerBank.Keys.Select(x => x).ToList();

var flattenedValues = customerBank.Values.Select(x => x).ToList();

}

I used Select rather than SelectMany to get indiviudual items by key or value as a list stored in a var, rather than a list of chars

Then you can process them indivudually like flattenedKeys[i].ToString() if you loop through them. Hope that helps.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: