How to create a query with Union using Nhibernate

Asked

Viewed 820 times

2

I need to implement a query in make a union between 2 tables. In , it would be something like that:

SELECT T1.Id AS ID
FROM TABELA1 AS T1
UNION    
SELECT T2.Id AS ID
FROM TABELA2 AS T2

I couldn’t find any way to make one union, nor with QueryOver, nor with Linq.

Someone knows something that can help me?

Edit 1

With Linq I even came up with an "almost" solution, but an error occurred saying that Union is not supported by . What I did was this:

var query = (from t1 in Session.Query<Tabela1>()
             select t1.Id
             ).Union(from t2 in Session.Query<Tabela2>()
                     select t2.Id);
query.ToList();

The mistake was this:

The Unionresultoperator result Operator is not Current supported

I don’t even know which way to go now, maybe I’ll have to do both selects separated and the union in remembrance.

1 answer

1


If you have control over the database, you could create a view in the database, which makes Union, and then map a class of yours to the view. This would solve the problem.

If it’s not that way, I guess I’m just doing it in memory.

According to that answer in the SOEN, it is possible to use the method Future to make two queries on the same call to the bank, which would be better than making two separate calls. Still, all results would be returned, without eliminating duplicates, which would have to be done in memory.

var resultSet1 = this.Session.CreateCriteria<A>().Future<A>();
var resultSet2 = this.Session.CreateCriteria<B>().Future<B>();

Unfortunately, according to this another SOEN response, cannot be used Future with LINQ, until version 3, so it seems that the only way at the moment is to use the above syntax.

  • Yes I’ve seen some people doing this, but I’m building a web service, to control synchronization of local data (legacy system) with a remote sales system (offline), and I need this union for query of deleted or inattentive items in the system. And so I have 2 queries, one for deleted in an audit table, which stores the identifiers of the deleted records, by period, and another for the records marked with an inactive database flag, also filtered by period. Then this query will be for a large amount of entities.

  • I’m testing the case of doing in memory following this issue of SOEN, in the answer accepted. I made an example here and apparently it is working perfectly, but even so it would be better to do it directly in the database. But every tip to improve is welcome. I’ll take a look at the tip you went through and see if it’s better for my case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.