views:

42

answers:

2

I'm using nHibernate with c# to get a list of records or strings from the database as show in the first couple of lines of code below. This works fine. What I want to do is select a few specific fields from the record and not the entire record. I have tried various techniques and can't seem to find any examples on how to do this. Could someone have a look at the code below and let me know if I am going off in the wrong direction.

Thanks!

//  THIS WORKS - Retrieve a list of my records from the table.
Ilist<MyClass> classList = db.Session.CreateQuery("FROM MyTable WHERE t.Name='AName'").List<MyClass>();


//  THIS WORKS - Retrieve a list of strings from the table
IList<string> stringList = db.Session.CreateQuery("SELECT c.ConstName FROM MyTable c WHERE c.Name='AName'").List<string>();


//  THIS DOES NOT WORK (RUN-TIME ERRORS).  HOW CAN I SELECT ONLY A FEW FIELDS FROM EACH RECORD?
//  This class contains only the records I want.
public struct MyClassB
{
    private string Name;
    private string Address;

    public string Name
    {
        get { return Name; }
        set { Name = value; }
    }

    public string Address
    {
        get { return Address; }
        set { stationName = Address; }
    }
}      


IList<MyClassB> classListB = db.Session.CreateQuery("SELECT t.Name, t.Address FROM MyTable t WHERE t.Name='AName'").List<MyClassB>();
+1  A: 

Have a look at the AliasToBeanResultTransformer - usage is demonstrated here.

DanP
+1  A: 

You are trying to cast an Anonymous type into your MyClassB which isn't valid. Instead create a mapping for MyClassB.

Or just use:

var specificFields = db.Session.CreateQuery("SELECT t.Name, t.Address FROM MyTable t WHERE t.Name='AName'").List();

var specificFields = db.Session.CreateQuery("SELECT t.Name, t.Address FROM MyTable t WHERE t.Name='AName'").List<Tuple<string,string>>();

The objects in the list will have the two properties.

Goblin
Could you elaborate on the mapping part? This works and I end up with an Array of Objects of Objects. I would think I could access the fields by doing a specificFields[record][field], but the compiler won't allow indexing of type object.
Ted N
The mapping part: You simply need to create a mapping for MyClassB that points at the same table that MyClassA uses, and then only map the two properties of MyClassB (and the Identiy part of course). Just be sure not to allow updates and deletes for MyClassB as it doesn't have all rows...
Goblin