NHibernate Collection Left Outer Join Where Clause Issue - asp.net

It seems that when using the following NHibernate query, I do not get a root entity when the left outer join has no records.
ICriteria critera = session.CreateCriteria(typeof(Entity));
criteria.CreateCriteria("SubTable.Property", "Property", NHibernate.SqlCommand.JoinType.LeftOuterJoin);
criteria.Add(Expression.Not(Expression.Eq("Property", value)));
The SQL that I am trying to generate is:
SELECT * FROM BaseTable
LEFT JOIN (
SELECT * FROM SubTable
WHERE Property <> value
)Sub ON Sub.ForeignKey = BaseTable.PrimaryKey
Notice that the where clause is inside the left join's select statement. That way if there arent any maching sub records, we still get a top level record. It seems like NHibernate is producing the following SQL.
SELECT * FROM BaseTable
LEFT JOIN (
SELECT * FROM SubTable
)Sub ON Sub.ForeignKey = BaseTable.PrimaryKey
WHERE Sub.Property <> value
Is there anyway to achieve that first piece of SQL? I have already tried:
ICriteria critera = session.CreateCriteria(typeof(Entity));
criteria.CreateCriteria("SubTable.Property", "Property", NHibernate.SqlCommand.JoinType.LeftOuterJoin);
criteria.Add(
Restrictions.Disjunction()
.Add(Expression.IsNull("Property"))
.Add(Expression.Not(Expression.Eq("Property", value)));
I am looking for a solution using the Criteria API.

Try this:
var hql = #"select bt
from BaseTable bt
left join bt.SubTable subt
with subt.Property <> :property";
Or perhaps:
var hql = #"select bt
from BaseTable bt
left join bt.SubTable subt
where subt.ForeignKey = bt.PrimaryKey
and subt.Property <> :property";
Finally:
var result = session.CreateQuery(hql)
.SetParameter("property", "whateverValue")
.List<BaseTable>();

I don't use nHibernate but I think this is the SQL you need to generate:
SELECT *
FROM BaseTable
LEFT JOIN SubTable sub
ON Sub.ForeignKey = BaseTable.PrimaryKey and sub.Property <> value
What you want isn;t a where clasue but an additional condition on the join. Hope that helps.

Related

EF Core - Count from a specific column

I almost have my EF Core query working... This is the SQL getting produced (notice the Count(*):
SELECT [u].[Key], [u].[Url], [u].[CreatedBy], [u].[CreatedOn], COUNT(*) AS [Clicks]
FROM [URLs] AS [u]
LEFT JOIN [OwnerUrls] AS [o] ON [u].[Key] = [o].[ShortUrlKey]
LEFT JOIN [Clicks] AS [c] ON [u].[Key] = [c].[ShortUrlKey]
GROUP BY [u].[Key], [u].[Url], [u].[CreatedBy], [u].[CreatedOn]
What I need is (have Count look at a specific column/table)
SELECT [u].[Key], [u].[Url], [u].[CreatedBy], [u].[CreatedOn], COUNT(c.ID) AS [Clicks]
FROM [URLs] AS [u]
LEFT JOIN [OwnerUrls] AS [o] ON [u].[Key] = [o].[ShortUrlKey]
LEFT JOIN [Clicks] AS [c] ON [u].[Key] = [c].[ShortUrlKey]
GROUP BY [u].[Key], [u].[Url], [u].[CreatedBy], [u].[CreatedOn]
Here is the EF Query that I'm using...
query = (from u in db.URLs
join ou in db.OwnerUrls on u.Key equals ou.ShortUrlKey into urlOwners
from subSet in urlOwners.DefaultIfEmpty()
join c in db.Clicks on u.Key equals c.ShortUrlKey into urlClicks
from subClicks in urlClicks.DefaultIfEmpty()
group subClicks by new { u.Key, u.Url, u.CreatedBy, u.CreatedOn } into g
select new ShortURL()
{
Key = g.Key.Key,
Url = g.Key.Url,
CreatedBy = g.Key.CreatedBy,
CreatedOn = g.Key.CreatedOn,
Clicks = g.Count()
});
I've tried changing the g.Count() to g.Select(x=>x.Id).Count() and that just causes EF Core to barf and complain about client side evaluation vs server side evaluation etc..
I should mention that the reason I'm joining the first model (OwnerUrls) is to support a where clause that I didn't include here...
Thanks!
I'm not a EF developer, but have worked with SQL Server for a while now. In SQL Server i would use COUNT(DISTINCT c.ID) to eliminate any duplicates you might get from JOINS.
If duplicates are impossible due to the model the COUNT(*) shoud be sufficient.
Maybe this might help:
https://entityframeworkcore.com/knowledge-base/51892585/linq-select-distinct-count-performed-in-memory

Complex AX Query

i want to rebuild this SQL Query as AX Query.
I tried it in several ways, but I don't get it.
I am not completely new to AX queries, but I only have experience with some simple queries not with such complex SQL queries.
SELECT * FROM ( SELECT DH.[RECID] AS RECID_DIMENSIONHIERARCHY
,DH.[NAME] AS NAME__DIMENSIONHIERARCHY
,DH.[DESCRIPTION] AS DESC__DIMENSIONHIERARCHY
,DH.[PARTITION] AS PARTITION_DIMENSIONHIERARCHY
,DL.[DIMENSIONATTRIBUTE] AS RECID_DIMENSIONATTRIBUTE
,DA.[NAME] AS NAME_DIMENSIONATTRIBUTE
,DN.[RECID] AS RECID_DIMENSIONCONSTRAINTNODE
,DNC.[RECID] AS RECID_DIMENSIONCONSTRAINTNODECRITERIA
,DNC.[RANGETO] AS #Owner
,DNCR.[WILDCARDSTRING] AS #Agreement
FROM (SELECT * FROM [dbo].[DIMENSIONHIERARCHY]
WHERE [STRUCTURETYPE] = 1 AND [NAME] LIKE 'AG-OW%'
) AS DH
INNER JOIN [dbo].[DIMENSIONHIERARCHYLEVEL] AS DL
ON DH.[RECID] = DL.[DIMENSIONHIERARCHY]
AND DH.[PARTITION] = DL.[PARTITION]
INNER JOIN [dbo].[DIMENSIONATTRIBUTE] AS DA
ON DL.[DIMENSIONATTRIBUTE] = DA.[RECID]
AND DL.[PARTITION] = DA.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODE] AS DN
ON DL.[RECID] = DN.[DIMENSIONHIERARCHYLEVEL]
AND DL.[PARTITION] = DN.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODECRITERIA] AS DNC
ON DN.[RECID] = DNC.[DIMENSIONCONSTRAINTNODE]
AND DN.[PARTITION] = DNC.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODECRITERIA] AS DNCR
ON DN.[PARENTCONSTRAINTNODE] = DNCR.[DIMENSIONCONSTRAINTNODE]
AND DN.[PARTITION] = DNCR.[PARTITION]
) AS Sub
You need to break down your query and implement it in small chunks. Then combine all of it to get the desired result.
There are two ways to create query in X++.
Create query using select statement for example:
Select * from HcmWorker join * from DirPerson
where DirPerson.RecId == HcmWorker.Person
See this link : Select statement syntax
Create query with AOT structure. You might want to have a look at the following link:
Create query in AOT by using X++

Search for empty fields on a table

I tried the command below. It's a DataSource of a GridView and it's written on my .aspx page, so I can not use characters like "" or ''. This code does not return me anything. I also tried to pass (string.empty, "" and null) as parameters in the codebehind. Nothing worked and I don't know what else to do...
SelectCommand="SELECT ch.id, sit.descricao as situacao, resp.responsavel, ch.dt_cadastro, ch.previsao_termino, func.descricao as funcionalidade,
proj.descricao as projeto ,pr.id as prid, pr.prioridade, clb.clube
FROM chamados AS ch
INNER JOIN prioridades as pr ON ch.prioridade = pr.id
INNER JOIN clubes as clb ON ch.clube = clb.id
INNER JOIN responsaveis as resp ON ch.responsavel = resp.id
INNER JOIN situacoes as sit ON ch.situacao = sit.id
INNER JOIN projetos as proj ON ch.projeto = proj.id
INNER JOIN funcionalidades as func ON ch.funcionalidade = func.id WHERE ch.responsavel IS NULL"
Obs:the field I want to filter as null they are int32 fields.
( I know that int32 can't be null) But I just didn't know what to do, so I tried everything that came to mind.
This query will always return no results because you use INNER JOIN in this statement:
INNER JOIN responsaveis as resp ON ch.responsavel = resp.id
and use the WHERE statenent where you compare one of INNER JOIN fileds with NULL
WHERE ch.responsavel IS NULL
The INNER JOIN joins ONLY fields which are NOT NULL. So these two statement except each other.
I found out the problem, it was:
I'm using INNER JOINS and as #valex told me:
The INNER JOIN joins ONLY fields which are NOT NULL. So these two statement except each other.
The solution was change the INNER JOIN for LEFT JOIN and worked like a charm !
Thanks everyone !

asp sqldatasource text

I need to have a sqldatasource with the following sql in it.
if #filter = 'departments'
begin
SELECT ISNULL(DocTitle,'') as Name, DocNumber as id, DocUrl+DocName AS link,LastModBy,LastModDate, IsLink
FROM cmc.CMC_Docs d
INNER JOIN CMC.CMC_Doc_Locations as l on l.FamilyID = d.FamilyID
INNER JOIN CMC.CMC_DocFamilies df on df.FamilyID = d.FamilyId
WHERE IsEnabled=1
AND ISNULL(DocName,'') <> ''
AND d.FamilyID IN #dep
ORDER by DocTitle
end
where #dep is something like (2,3)
However when I try to test the query I get an error saying incorrect syntax near #dep.
Any ideas how I need to write this inside of the datasource in order for it to work?
Thanks,
do you need to put this in ()?
ex: select * from product where productid in (1,2,3) works
ex: select * from product where productid in 1,2,3 - does not work

Count the number of elements in sql server table

I have 2 tables which looks like this:
ARTICLES TABLE:
and the output should look like this:
How can I accomplish this using both sql query (i'm using sql server 2005) and using linq to sql query ?
BTW i'm using sql server 2005, asp.net with c# in Visual studio 2008.
Please help me
Thanks in anticipation
Update: Added Linq experssion that can be used if you require an OUTER join.
INNER JOIN
For an inner join ie. only get back the articles that have been bought at least once, you can use the following.
LINQ 2 SQL
from a in Articles
join c in CustomersRecords on
a.Article_Name equals c.Article_Name
group a by new {a.SNo, a.Article_Name} into g
select new
{
SNo = g.Key.SNo,
Article_Name = g.Key.Article_Name,
Total_Items_Bought = g.Count()
}
The above translates to the following SQL
SELECT COUNT(*) AS [Total_Items_Bought], [t0].[SNo], [t0].[Article_Name]
FROM [Articles] AS [t0]
INNER JOIN [CustomersRecord] AS [t1] ON [t0].[Article_Name] = [t1].[Article_Name]
GROUP BY [t0].[SNo], [t0].[Article_Name]
Which when cleaned-up a little gives you
SELECT a.SNo,
a.Article_Name,
COUNT(*) AS Total_Items_Bought
FROM Articles AS a
INNER JOIN CustomersRecord AS c ON a.Article_Name = c.Article_Name
GROUP BY a.SNo, a.Article_Name
LEFT OUTER JOIN
For a left outer join ie. get back all articles event those that have never been bought, you can use the following.
LINQ 2 SQL
from a in Articles
join c in CustomersRecords on
a.Article_Name equals c.Article_Name into apc
select new
{
SNo = a.SNo,
Article_Name = a.Article_Name,
Total_Items_Bought = apc.Count()
}
This translates to the following SQL
SELECT [t0].[SNo], [t0].[Article_Name], (
SELECT COUNT(*)
FROM [CustomersRecord] AS [t1]
WHERE [t0].[Article_Name] = [t1].[Article_Name]
) AS [Total_Items_Bought]
FROM [Articles] AS [t0]
select
A.SNo,
A.Article_Name,
count(C.Article_Name) as Total_Items_Bought
from Articles as A
left outer join CustomersRecord as C
on A.Article_Name = C.Article_Name
group by A.SNo, A.Article_Name
order by A.SNo
Use this for SQL
SELECT
SNO,Article_Name,
(SELECT COUNT(*) FROM CustomersRecord AS cr
WHERE cr.Article_Name = Article_Name) AS Total_Items_Bought
FROM ARTICLES

Resources