简体   繁体   English

从 NHibernate QueryOver SelectList 调用对象构造函数

[英]Calling an object constructor from NHibernate QueryOver SelectList

I have a DTo class UserDTO with the following constructor public UserDTO(User user) .我有一个UserDTOUserDTO和以下构造函数public UserDTO(User user) I have also created an NHibernate query which retrieves a IList<TodoDTO> where each TodoDTO has the following property public IList<UserDTO> ResponsibleUsers { get; set; }我还创建了一个 NHibernate 查询,它检索一个IList<TodoDTO> ,其中每个TodoDTO具有以下属性public IList<UserDTO> ResponsibleUsers { get; set; } public IList<UserDTO> ResponsibleUsers { get; set; } public IList<UserDTO> ResponsibleUsers { get; set; } . public IList<UserDTO> ResponsibleUsers { get; set; } . I am wondering if it would be possible to this constructor on UserDTO in my query, so something like this:我想知道在我的查询中是否可以在UserDTO上使用这个构造函数,所以是这样的:

var responsibleUsers = session.QueryOver<UserTodo>()
    .JoinAlias(ut => ut.User, () => userAlias)
    .Where(ut => ut.Todo.Id.IsIn(_todos.Select(t => t.Id).ToArray()))
    .Select(u => new UserDTO(userAlias)).ToList<UserDTO>();

The constructor looks like this:构造函数如下所示:
public UserDTO(User user) {}

The problem is that when I run this code the parameter in the UserDTO constructor the user is null.问题是,当我运行此代码时, UserDTO构造函数中的参数user为空。

Calling a Constructor, (or any other code) in the syntax of a query won't work.在查询的语法中调用构造函数(或任何其他代码)将不起作用。 the entities here are only used to resolve the table and columns for the sql query.这里的实体仅用于解析 sql 查询的表和列。 The ability to call methods of these objects is missleading...调用这些对象的方法的能力是误导...

You can use a Projection to select data from one, or multiple db-entities to a new object (in your case: to the UserDTO)您可以使用 Projection 从一个或多个 db-entities 中选择数据到新对象(在您的情况下:到 UserDTO)

UserTodo userTodo = null
UserDTO result = null;
var responsibleUsers = session.QueryOver<UserTodo>(() => userTodo)
 .JoinAlias(ut => ut.User, () => userAlias)
 .Where(ut => ut.Todo.Id.IsIn(_todos.Select(t => t.Id).ToArray()))
 .SelectList(list => list
  .Select(() => userAlias.FirstName).WithAlias(() => result.FirstName)
  .Select(() => userAlias.UserId).WithAlias(() => result.IdOfUser)
  .Select(() => userTodo.Age).WithAlias(() => result.Age) // if you require any values from UserTodo
)
.TransformUsing(Transformers.AliasToBean<UserDTO >())
.List<UserDTO >();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM