简体   繁体   中英

Calling an object constructor from NHibernate QueryOver SelectList

I have a DTo class UserDTO with the following constructor 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; } 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:

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.

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. 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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