从数据库中获取对象中的单个属性 [英] fetch single property in object from database

查看:44
本文介绍了从数据库中获取对象中的单个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 NET MVC 3.0 和 Nhibernate 3.0.我只想从数据库中获取一个属性到一个对象.

I am working on NET MVC 3.0 and Nhibernate 3.0. I want to fetch only one property from database to an object.

例如,假设我有一个类模块.我想从模块表中选择所有名称(如 select modulename from module 查询)并准备一个只有名称的模块对象列表.所有其他属性都可以是 null.

For instance, suppose I have a class Module. I want to select all the names from module table (like select modulename from module query) and an prepare a list of module objects which have only name. All other properties can be null.

我使用 QueryOver API 尝试了这个:

I tried this using QueryOver API:

IQueryOver<ProjectModule> module = session.QueryOver<ProjectModule>()
    .Select(a=>a.Name)                   
    .TransformUsing(
        NHibernate.Transform.Transformers.AliasToBean<ProjectModule>());

pm = module.List<ProjectModule>();

pmIList 类型.

事务已成功提交.没有发生错误,但我得到了一个包含所有属性 = null 的模块对象列表.模块名称null,模块id null

Transaction gets committed successfully. No error occurred, but I get a list of module objects with all properties = null. Module name null, module id null etc.

我使用 NUnit 检查了在 SQL 上执行的查询并得到以下信息:SELECT this_Name as y0_ FROM ProjectModule this_.

I checked what query is executing on SQL using NUnit and got this: SELECT this_Name as y0_ FROM ProjectModule this_.

推荐答案

为了更准确地创建 DTO 对象,假设 ProjectModuleDto,它将只包含 Name.通过代码使用具有未初始化值的域对象不是一个好习惯,因为它会在各种场景中造成填充数据的混淆.

To be more accurate create a DTO object, assume ProjectModuleDto, that will contain only the Name. It's not a good practice to use the the domain object with uninitialized values through your code, cause it creates confusions of filled data in various scenarious.

流动的代码将起到作用 - 填充 DTO 列表:ProjectModuleDto 使用数据库中正确的项目模块名称:

And the fllowing code will do the trick - populate the list of DTOs: ProjectModuleDto with correct Name of project module from database:

ProjectModuleDto projectModuleDto = null;           
IQueryOver<ProjectModule> module = session.QueryOver<ProjectModule>()
    .SelectList(
        list=>list.Select(a => a.Name).WithAlias(() => projectModuleDto.Name)
    )                 
    TransformUsing(NHibernate.Transform.Transformers.AliasToBean<ProjectModuleDto>());

pm = module.List<ProjectModuleDto>();           

这篇关于从数据库中获取对象中的单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆