【问题标题】:Getting single column from an entity从实体中获取单列
【发布时间】:2016-02-28 15:13:03
【问题描述】:

如何从查询中获取单个列而不是整个对象?

我可以这样做来获取整个对象,但我想要的只是名称:

IList<Tribble> tribbles = session.CreateCriteria(typeof(Tribble)).List<Tribble>();
IList<string> names = new List<string>();
foreach (Tribble t in tribbles) {
    names.Add(t.Name);
}

我希望能够指定其他条件,那么是否可以只排除某些列而不被检索?

【问题讨论】:

    标签: c# nhibernate


    【解决方案1】:

    这是我最终使用的解决方案:

    ICriteria c = session.CreateCriteria(typeof(Tribble));
    c.SetProjection(Projections.ProjectionList().Add(Projections.Property("Name")));
    IList<string> names = c.List<string>();
    

    我从this old StackOverflow question得到这个想法。

    【讨论】:

      【解决方案2】:

      大约五年后...,这就是您可以使用 NHibernate.Linq 做的事情:

      IList<string> names = session.Query<Tribble>().Select(t => t.Name).ToList()
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        IQuery query = dao.GetQuery(@"SELECT u.Id
                                        FROM UserImpl u
                                       WHERE u.UserName = :username");
                       query.SetParameter("username", username);
        return (long)query.UniqueResult();
        

        【讨论】:

          【解决方案4】:

          按字符串执行查询呢?

          IList<string> names = session.CreateQuery("select name from Tribbles").List<string>();
          

          【讨论】:

          • 从技术上讲,您实际上必须这样做: IList names = session.CreateQuery("select t.name from Tribbles t").List();
          【解决方案5】:

          你通常不会。拥有部分填充的业务对象几乎没有意义。

          你为什么要这样做?

          【讨论】:

          • 我在整个程序中使用它,有几十个类,这是我唯一一次需要这样做,在这种情况下是必要的。
          • 你能进一步解释一下用例是什么吗?
          • 这种情况不是经常发生吗?例如,我想显示员工的详细信息以及其办公室的名称。我不需要整个办公室,只需要名字。
          • @cbp:它确实一直在发生。假设 Employee 被映射为 m:1 到 Office,NHibernate 将在使用连接加载 Employee 时检索 Office。使用业务对象时,您总是返回完全填充的对象(当然也有例外)。这正是面向对象编程的方式。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-25
          相关资源
          最近更新 更多