QueryOver - JoinQueryOver problems - nhibernate

i How to use queryover (Join) for same table...example
if (!string.IsNullOrEmpty(ufResidencia) ||
!string.IsNullOrEmpty(cidadeResidencia))
{
EnderecoProspect endPros = null;
TipoEndereco tipoEnd = null;
query
.JoinQueryOver<EnderecoProspect>(x => x.Enderecos,()=> endPros)
.And(()=> endPros.Uf ==ufResidencia)
.JoinQueryOver<TipoEndereco>(x => x.TipoEndereco,()=> tipoEnd)
.And(()=> tipoEnd.Descricao != "Fazenda");
}
if (!string.IsNullOrEmpty(ufFazenda) ||
!string.IsNullOrEmpty(cidadeFazenda))
{
EnderecoProspect endPros1 = null;
TipoEndereco tipoEnd1 = null;
query
.JoinQueryOver<EnderecoProspect>(x => x.Enderecos,()=> endPros1)
.And(()=> endPros1.Uf ==ufFazenda)
.JoinQueryOver<TipoEndereco>(x => x.TipoEndereco,()=> tipoEnd1)
.And(()=> tipoEnd1.Descricao == "Fazenda");
}
When I try to run I get the message that the path is duplicated. Im using alias correct? what problem? havy ideal? exception is "duplicate association path"

I managed to solve with LINQ to NHibernate ... there is the example for all ...
var q =
from c in Context.Query<Prospect>()
join o in Context.Query<EnderecoProspect>() on c.Identificacao equals o.Prospect.Identificacao
join e in Context.Query<TipoEndereco>() on o.TipoEndereco.Identificacao equals e.Identificacao
join a in Context.Query<EnderecoProspect>() on c.Identificacao equals a.Prospect.Identificacao
join b in Context.Query<TipoEndereco>() on a.TipoEndereco.Identificacao equals b.Identificacao
where (
(
(o.Uf == ufFazenda || ufFazenda == null) &&
(o.Cidade == cidadeFazenda || cidadeFazenda == null)
) && e.Descricao == "Fazenda"
)
&&
(
(
(a.Uf == ufResidencia || ufResidencia == null) &&
(a.Cidade == cidadeResidencia || cidadeResidencia == null)
) && b.Descricao != "Fazenda"
)
Now I can sleep a little more until ...ehehehe...see you

Related

Entity Framework Union And Paging

I am getting the result query by running two queries and joining them with union clause. I have to use paging but I need results as inserted line. I don't want to order it again. But when I use paging I have to use order by clause. how can I get results with natural order.
var prodFullTextQuery = _db.Products
.Where(x => !x.IsDeleted
&& x.ProdStatusValue == (int)ProdStatus.Active
&& (x.ProdName.Contains(searchText)
|| x.Keywords.Contains(searchText)
|| x.ManufacturerCode.StartsWith(searchText)
));
IQueryable<Product> prodQuery;
prodQuery = _db.Products.Where(x => !x.IsDeleted
&& x.ProdStatusValue == (int)ProdStatus.Active
&& x.VariantMainProdId == x.ProdId);
foreach (var s in searchText.Split(' '))
{
var temp = s;
prodQuery = prodQuery.Where(x => x.Keywords.Contains(temp));
}
prodFullTextQuery = prodFullTextQuery.Union(prodQuery)
//i need here by the order in which rows are inserted
var results= prodFullTextQuery
.OrderBy(x=>x.OrderId) //i don't want this
.Skip(prodCountPerPage * pageNumber)
.Take(prodCountPerPage)
.ToList()

sql query vs linq to entity return different results

This is my sql query
SELECT TOP(10)projects.stat,
wo.stat,
sevt.restype,
sevt.resid,
restype.user2,
projects.prj_id,
projects.user3,
projects.user9,
wo.wonum,
wo.jobdesc,
sevt.sesid,
sevt.restype,
sevt.type,
sevt.t_start,
sevt.t_end,
sevt. mealstart,
sevt.mealend,
sevt. melstart2,
sevt.melend2,
sevt.melstart3,
sevt.melend3,
sevt.user2,
sevt.subactid,
sevt.ot_exempt,
sevt_ex.user5,
rescat.user1
FROM schedwin.projects
INNER JOIN schedwin.wo
ON projects.prj_id = wo.prj_id
INNER JOIN schedwin.sevt
ON wo.seqnum = sevt.seqnum
INNER JOIN schedwin.rsrce
ON sevt.resid = rsrce.resid
LEFT OUTER JOIN schedwin.pers
ON rsrce.recid = pers.recid
INNER JOIN schedwin.restype
ON sevt.rtype = restype.code
INNER JOIN schedwin.rescat
ON sevt.rcat = rescat.code
LEFT OUTER JOIN schedwin.sevt_ex
ON sevt.sesid = sevt_ex.sesid
WHERE ( Ltrim(Rtrim(projects.stat)) IN ( '1', '2' ) )
AND ( Ltrim(Rtrim(wo.stat)) = '6' )
AND ( ( ( sevt.restype = 5
OR sevt.restype = 0 )
AND ( Substring(restype.user2, 2, 1) = 'F'
AND Substring(restype.user2, 6, 1) = 'S' ) )
OR ( sevt.restype = 4 ) )
AND ( sevt.type = 0 )
AND rescat.groupid = 0
AND restype.groupid = 0
AND Len(Ltrim(wo.invoice)) > 0
AND Ltrim(wo.invoice) <> 'PENDING'
AND wo.userflag1 <> 1
AND Ltrim(sevt.t_start) = '1351728000'
ORDER BY projects.prj_id,
wo.wonum
I was converting in to Linq to Entity like below
var query =
(from PROJECTS in db.PROJECTS
join WOes in db.WOes on PROJECTS.PRJ_ID equals WOes.PRJ_ID
join SEVTs in db.SEVTs on WOes.SEQNUM equals SEVTs.SEQNUM
join RSRCEs in db.RSRCEs on SEVTs.RESID equals RSRCEs.RESID
join PERS in db.PERS on RSRCEs.RECID equals PERS.RECID into PERS_join
from PERS in PERS_join.DefaultIfEmpty()
join RESTYPEs in db.RESTYPEs on new { RTYPE = SEVTs.RTYPE } equals new { RTYPE = RESTYPEs.CODE }
join RESCATs in db.RESCATs on new { RCAT = SEVTs.RCAT } equals new { RCAT = RESCATs.CODE }
join SEVT_EX in db.SEVT_EX on SEVTs.SESID equals SEVT_EX.SESID into SEVT_EX_join
//join SEVT_EX in db.SEVT_EX on new { SESID = (String)SEVTs.SESID } equals new { SESID = SEVT_EX.SESID } into SEVT_EX_join
from SEVT_EX in SEVT_EX_join.DefaultIfEmpty()
where
(new string[] { "1", "2" }).Contains((PROJECTS.STAT.TrimEnd()).TrimStart()) &&
((WOes.STAT.TrimEnd()).TrimStart() == "6") &&
(((SEVTs.RESTYPE == 5 || SEVTs.RESTYPE == 0) &&
(RESTYPEs.USER2.Substring(2 - 1, 1) == "F" && RESTYPEs.USER2.Substring(6 - 1, 1) == "S")) || (SEVTs.RESTYPE == 0)) &&
(SEVTs.TYPE == 0) &&
(RESCATs.GROUPID == 0) &&
(RESTYPEs.GROUPID == 0 )&&
(int?)(WOes.INVOICE.TrimStart()).Length > 0 &&
WOes.INVOICE.TrimStart() != "PENDING" &&
WOes.USERFLAG1 != 1 &&
(SEVTs.T_START.TrimStart()) == (Booktime)
//(SEVTs.T_START.TrimStart()) == (Booktime)
// String.Compare(SEVTs.T_START.ToString().TrimStart(), "1351728000") >= 0
//Convert.ToInt32(SEVTs.T_START.TrimStart()) >= Convert.ToInt32(Booktime)
orderby
PROJECTS.PRJ_ID,
WOes.WONUM
select new
{
PROJECTS.PRJ_ID,
PROJECTS.USER3,
PROJECTS.USER9,
WOes.WONUM,
WOes.JOBDESC,
SEVTs.SESID,
SEVTs.RESTYPE,
SEVTs.TYPE,
SEVTs.T_START,
SEVTs.T_END,
SEVTs.MEALEND,
SEVTs.MELSTART3,
SEVTs.MELSTART2,
SEVTs.MELEND2,
Column1 = SEVTs.MELSTART2,
SEVTs.MELEND3,
SEVTs.USER2,
SEVTs.SUBACTID,
SEVTs.OT_EXEMPT,
USER5 = SEVT_EX.USER5,
SEVTs.GMT_OFFSET,
SEVTs.MEALSTART,
SEVTs.STANDARD,
RESCATs.USER1,
SEVTs.RESID
}).Take(10);
Definitely my sql query is return a correct records back but my Linq is not, any have any clue what am missing here please ?
Thanks
You have this line:
(((SEVT.restype = 5 or SEVT.restype = 0) and (substring(restype.User2,2,1) = 'F' and substring(restype.User2,6,1) = 'S')) or (SEVT.RESTYPE = 4))and
and in linq you have this
((SEVTs.RESTYPE == 5 || SEVTs.RESTYPE == 0) && (RESTYPEs.USER2.Substring(2 - 1, 1) == "F" && RESTYPEs.USER2.Substring(6 - 1, 1) == "S") && SEVTs.TYPE == 0)
First, Substring in 2-1 = 1 not 2. and the Logical Operations not equal

Binary Search Tree Delete Node With One Child

I have a binary search tree and when I try to do the case where you delete a node with a single child, you delete that node and move the child node in it's place. I have the code for it but it's giving me a bad pointer whenever I do it.
This is the segment of the code
else if((root->Left != NULL) != (root->Right != NULL)){ //Checks if it's a on child node
if(root->Left != NULL){ //If it has a left child, attempts to move the left child to existing node
delete root;
root = root->Left;
}
else{ //If it is right child, attempts to move right child to existing node
delete root;
root = root->Right;
}
}
The struct has values
DATA_TYPE Value;
TreeNode* Left;
TreeNode* Right;
I know I'm allocating it wrong from the debugger, so what's the correct way to move the node?
Edit:
Don't know how I missed it but you're using root right after deleting it.
Edit2:
You need a temporary.
TreeNode* temp = root->Right;
delete root;
root = temp;
Here is a Java implementation for the method
public void removeHalfNodes () {
if ( root == null ) return;
if ( root.left == null && root.right == null ) return;
if ( root.left == null && root.right != null ) root = root.right;
else if ( root.left != null && root.right == null )
root = root.left;
removeHalfNodesRec ( root );
}
public void removeHalfNodesRec ( BinaryTreeNode node ) {
if ( node.left != null ) {
if ( node.left.left == null && node.left.right != null )
node.left = node.left.right;
else if ( node.left.right == null && node.left.left != null )
node.left = node.left.left;
removeHalfNodesRec ( node.left );
}
if ( node.right != null ) {
if ( node.right.left == null && node.right.right != null )
node.right = node.right.right;
else if ( node.right.right == null && node.right.left != null )
node.right = node.right.left;
removeHalfNodesRec ( node.right );
}
}

How to create a Dynamic Query when there's a condition that won't use all fields in the where section with LinQ

I am using a Data Entity from the db, and a Domain Service.
I am using .net's generated code for the simple queries, like this
public IQueryable<employee> GetEmployeesByLocale(int localeID)
{
return ObjectContext.employees.Where(e => e.Locale_ID == localeID);
}
Now, I need to change the .Where section accordingly, so:
if (localeID > 0)
{
['Where' should be like .Where(e => e.Locale_ID == localeID)];
}
if (projectID > 0)
{
[IF localeID == 0, 'Where' should be like .Where(e => e.Project_ID == projectID)
Else if localeID > 0, Where should use both, sort of .Where(e => e.Locale_ID == localeID && e.Project_ID == projectID)];
}
and so on with other variables.
There are many possible combinations , which is why I was trying to use the overload for .Where(string, parameter[])
string q = string.Empty;
if (localeID > 0)
{
q = "Locale_ID = " + localeID.ToString();
}
if (projectID > 0)
{
q = q == string.Empty ? "Project_ID = " + projectID.ToString() : q + " and " + "Project_ID = " + projectID.ToString();
}
... (for other variables and fields)
...
System.Data.Objects.ObjectParameter[] param = new System.Data.Objects.ObjectParameter[1];
param[0] = new System.Data.Objects.ObjectParameter("param", 1);
return ObjectContext.employees.Where(q, param);
However, this only gives an error, because then all the fieldnames are supposedly out-of-scope/non-existing. Even if use employees.[field_name] in the string, they "don't exist"
Does anyone know of a way to use conditionals inside the .Where part of the query? Or how to create some var or object containing my query so I can just parse it?
You can use
IQueryable<Employee> emp = ObjectContext.employees;
if (localeID > 0)
emp=emp.Where(e => e.Locale_ID == localeID).AsQueryable();
if (projectID > 0)
emp=emp.Where(e => e.Project_ID == projectID).AsQueryable();
This will concatenate the where clauses

Complex LINQ query from SQL

I have following SQL query:
SELECT Count(*) AS CountOfRecs FROM tblAccount INNER JOIN tblAccountOwner ON
tblAccount.[Creditor Registry ID] = tblAccountOwner.[Creditor Registry ID] AND
tblAccount.[Account No] = tblAccountOwner.[Account No] WHERE (tblAccountOwner.
[Account Owner Registry ID] = 731752693037116688) AND (tblAccount.[Account Type]
NOT IN ('CA00', 'CA01', 'CA03', 'CA04', 'CA02', 'PA00', 'PA01', 'PA02', 'PA03', 'PA04'))
AND (DATEDIFF(mm, tblAccount.[State Change Date], GETDATE()) <= 6
OR tblAccount.[State Change Date] IS NULL)
AND ((tblAccount.[Account Type] IN ('OD','CL00','PL00')) OR
(tblAccount.[Account Type] LIKE '%Overdra%'))
and I want to translate it to LINQ. I have created following LINQ but It is not returning same count. SQL is returning 2, LINQ is returning 0.
public int OverDraftCount(long AccountOwnerRegistryId = 731752693037116688)
{
CreditRegistryContext context = new CreditRegistryContext();
string notAllowedAccountTypes = "CA00, CA01, CA03, CA04, CA02, PA00, PA01, PA02, PA03, PA04";
var subList = notAllowedAccountTypes.Split(',');
string AllowedAccountTypes = "OD,CL00,PL00";
var subList1 = AllowedAccountTypes.Split(',');
var query = from c in context.AccountOwners
.Where(p => p.CreditorRegistryId == p.Account.CreditRegistryId
&& p.AccountNo == p.Account.AccountNo
&& p.AccountOwnerRegistryId == AccountOwnerRegistryId
&& !subList.Contains(p.Account.AccountType)
&& (EntityFunctions.DiffMonths(
p.Account.StateChangeDate, DateTime.Now) < 6
|| p.Account.StateChangeDate == null
&& (subList1.Contains(p.Account.AccountType)
|| p.Account.AccountType.Contains("Overdra"))))
select c;
return query.Count();
}
Please suggest solution.
Your parentheses were off in the last 4 lines of the Where clause:
var query = from c in context.AccountOwners
.Where(p => p.CreditorRegistryId == p.Account.CreditRegistryId
&& p.AccountNo == p.Account.AccountNo
&& p.AccountOwnerRegistryId == AccountOwnerRegistryId
&& !subList.Contains(p.Account.AccountType)
&& (EntityFunctions.DiffMonths(p.Account.StateChangeDate, DateTime.Now) < 6
|| p.Account.StateChangeDate == null)
&& (subList1.Contains(p.Account.AccountType)
|| p.Account.AccountType.Contains("Overdra")))
select c;