开发者

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<MyClas开发者_C百科s> 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>();


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜