Ted1391
Ted1391

Reputation: 139

nHibernate Select statement for specific fields

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>();

Upvotes: 1

Views: 5355

Answers (3)

Shagglez
Shagglez

Reputation: 1522

As long your class has a contructor you should be able to do the following:

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

Upvotes: -1

Goblin
Goblin

Reputation: 8022

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.

Upvotes: 0

DanP
DanP

Reputation: 6478

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

Upvotes: 2

Related Questions