NHibernate joins multiple tables and uses AliasToBean Transformer

I have a very simple need to get some data from a database and return a DTO. I found that joining multiple tables using nHibernate and "projecting" in DTO, so to speak, is quite a bit of code. After looking at a few examples, most of which did not work, leaving me a DTO with zero values, I hold on to the following and wonder if you can an nHibernate ninja tell me if there is a better way.

public IOpenIdUser GetOpenIdUser(string claimedIdentifier, IOpenIdUser openIdUserDto) { User user = null; OpenIdUser openIdUser = null; Profile profile = null; UserType userType = null; return SessionWrapper.Session.QueryOver(() => user).JoinAlias(() => user.Profiles, () => profile). JoinAlias(() => user.OpenIdUsers, () => openIdUser).JoinAlias(() => user.UserType, () => userType) .Where(() => user.UserName == claimedIdentifier) .SelectList(l => l .Select(x => openIdUser.OpenIdUserId).WithAlias(() => openIdUser.OpenIdUserId) .Select(x => user.UserId).WithAlias(() => openIdUserDto.UserId) .Select(x => openIdUser.OpenIdClaimedIdentifier).WithAlias( () => openIdUserDto.ClaimedIdentifier) .Select(x => openIdUser.OpenIdFriendlyIdentifier).WithAlias( () => openIdUserDto.FriendlyIdentifier) .Select(x => openIdUser.OpenIdEndPoint).WithAlias( () => openIdUserDto.OpenIdEndPoint) .Select(x => user.UserName).WithAlias(() => openIdUserDto.UserName) .Select(x => userType.Type).WithAlias(() => openIdUserDto.UserType) .Select(x => profile.DisplayName).WithAlias(() => openIdUserDto.DisplayName) .Select(x => profile.EmailAddress).WithAlias(() => openIdUserDto.EmailAddress) .Select(x => openIdUser.DateCreated).WithAlias(() => openIdUserDto.DateCreated) .Select(x => openIdUser.LastUpdated).WithAlias(() => openIdUserDto.LastUpdated) .Select(x => openIdUser.UsageCount).WithAlias(() => openIdUserDto.UsageCount) ).TransformUsing(Transformers.AliasToBean<OpenIdUserDto>()).Future<OpenIdUserDto>().Single(); } 

This method is in my UserRepository and is called by my UserService. Please, not that it really works, I just think that it is too much for such a simple task. Also note that I'm new to this, so if this code is crappy, I apologize in advance.

+6
source share
1 answer

If you are using Queryover, this is the only way.

If you really think that fewer lines of code are preferable, more intuitive, or sitting better with you, you can do this: -

  • Create a database view and create map files for the view using mutable="false" in your class definition and use the protected set; for class properties
  • Instead, use a LINQ provider, for example. .Query (see this blog post for more information)
+2
source

Source: https://habr.com/ru/post/908155/


All Articles