Error converting Linq parallequery to ienumerable - c#

Using Linqpad to work out my query, get the above error on:
(from bp in basepay_records
select new { empID = bp.Prep_emp, loc = bp.Prep_loc }).Union
(
from ass in emp_assignments
select new { empID = ass.Prea_emp, loc = ass.Prea_loc }
)
I have tried it with and without the paren on the first query, no diff. This union is part of a larger query, and this will end up sitting in a subquery that is used in a join, so I can't do the usual, though I did it test it as a stand alone query and it failed, saying no definition for Union:
var q1 = from bp in basepay_records select new { empID = bp.Prep_emp, loc = bp.Prep_loc };
var q2 = from ass in emp_assignments select new { empID = ass.Prea_emp, loc = ass.Prea_loc };
q1.Union (q2).Dump ("Union");
I confirmed that all the datatypes match.
Full error message is:
Cannot execute text selection: 'System.Linq.IQueryable' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union(System.Linq.ParallelQuery, System.Collections.Generic.IEnumerable)' has some invalid arguments
Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Linq.ParallelQuery'

I have it working now. I had to split it into 2 queries, which seems stupid, but there you go. Let me know if you have a beter way:
var q1 = from mstr in emp_master_records
join loctab in
(
from bp in basepay_records
select new { empID = bp.Prep_emp, loc = bp.Prep_loc }
)
on mstr.Prem_emp equals loctab.empID
where mstr.Prem_email.StartsWith("TEST_USER")
select loctab.loc;
var q2 = from mstr in emp_master_records
join loctab in
(
from ass in emp_assignments
select new { empID = ass.Prea_emp, loc = ass.Prea_loc }
)
on mstr.Prem_emp equals loctab.empID
where mstr.Prem_email.StartsWith("GREGORY_RANDALL")
select loctab.loc;
q1.Union(q2).Dump ("Union");

Related

ORA-00907: missing right parenthesis in LINQ

I have Linq query where I am trying to write subquery to set the value of item, I am encountering with error saying
{ORA-00907: missing right parenthesis
}, Please let me know the right syntax to make it work
var lst = (
from cr in dbContext.Company
orderby cr.COMPANY_KEY
select new CompanyDto()
{
CompanyKey = cr.CompanyKey,
CompanyCode = (from rc in dbContext.COMPANY_PORTFOLIOS where rc.PORTFOLIO == cr.P_PORTFOLIO select rc.COMPANY_CODE).FirstOrDefault()
}
);
var d = st.Skip(pageIndex).Take(pageSize).ToList();
Even the below piece of code is not working
var lst = (
from cr in dbContext.Company
orderby cr.COMPANY_KEY
select new CompanyDto()
{
CompanyKey = cr.CompanyKey,
CompanyCode = (from rc in dbContext.COMPANY_PORTFOLIOS where rc.PORTFOLIO == cr.P_PORTFOLIO select rc.COMPANY_CODE).Single()
}
);
var d = st.Skip(pageIndex).Take(pageSize).ToList();
I think you can just use a Join to achieve what you are looking to do:
var lst = (
from cr in dbContext.Company
orderby cr.COMPANY_KEY
join rc in dbContext.COMPANY_PORTFOLIOS on cr.PORTFOLIO equals rc.P_PORTFOLIO into myJoin
from rc in myJoin.DefaultIfEmpty()
select new CompanyDto()
{
CompanyKey = cr.CompanyKey,
CompanyCode = rc.COMPANY_CODE
}
);
var d = lst.Skip(pageIndex).Take(pageSize).ToList();
If the above still gives Oracle errors, put a breakpoint at the last line and get the SQL the linq generates. You can then paste this into something like Oracle SQL Developer and run the query, which may give you a more informative error message and allow you to track down the issue.

Dynamic SQL to LINQ Entity Framework

I have only the very basics of LINQ. I speak SQL and JDBC, tasked with converting dynamic PL/SQL to LINQ Entity Framework. How can I add conditional WHERE clauses into LINQ queries? Here is a very simplified example (leaving out type info):
Q1 := 'SELECT bDay = b.birthday
address = b.address
FROM (' ;
Q2 := 'SELECT folks.birthday, Address.address
FROM folks,
(SELECT state,
surname AS name
FROM Individuals, Addresses
WHERE Individuals.addrId = Address.id
AND Addresses.state = 'CA' ) find1
,(SELECT state,
surname AS name
FROM Individuals, Addresses
WHERE Individuals.addrId = Address.id
AND Addresses.state = 'NV' ) find2
AND find1.state(+) = folks.state';
IF input_parm = 'RED' THEN
condAddOn :=condAddOn || 'AND folks.vacationHouse IS NOT NULL';
END IF;
IF input_parm = 'BLUE' THEN
condAddOn :=condAddOn || 'AND folks.vacationHouse = 'Cabin';
END IF;
...
OPEN curs FOR Q1 || Q2 || condAddOn ')b';
Trying to figure out the C#/LINQ syntax, here is my attempt (working bottom up):
var find1 = (from addr in Addresses
from indiv in Individuals
where indiv.addrId = addr.addrID
select new
{
indiv.state,
indiv.surname
});
var find1OuterJoin = (from person in folks
join f1 in find1 on person.addrId equals f1.addrID
from f1OutJn in temp.DefaultIfEmpty()
select new
{
f1OutJn.state,
f1OutJn.surname
});
var Q2 = (from person in folks
from addr in addresses
from f1 in find1OuterJoin
where person.addrId == addr.addrId
&& f1.state == folks.state
select new
{
person.birthday
,addr.address
});
var Q1 = (from q2 in Q1
select new
{bDay = b.birthday
,address = b.address
});
I don't know
1) if I introduced Q1 into the Q2 correctly
2) how to introduce the dynamic WHERE clauses
to end up with an equivalent cursor statement:
OPEN curs FOR Q1 || Q2 || condAddOn ')b';
Added: Can I use a functional or expression to include the dynamic bits? I saw a reference to Expression and Expandable(), but unsure.
Added: my attempt at the LINQ queries
When using the where method with link you are returned an IQueryable object. This does not immediately execute the statement, therefore it is possible to do the following:
var results = from person in folks
join addr in addresses
where person.addrId == addr.addrId
select new {
person.birthday,
addr.address
};
if(predicate){
results = from r in results
where /* new condition here */
select r;
}
var resultSet = results.ToList().AsEnumerable();
for other link operators, especially when using lambda linq you can also use the AsQuerably extension method.
such as, but not limited to:
var results = folks.join(address,
person => person.addrId,
addr => addr.addrId
(person, addr) => new {
person.birthday,
addr.address
}).AsQueryable();
if(predicate)
{
results = results.where(/*predicate for the where condition*/);
}
var resultSet = results.ToList().AsEnumerable();

Type inference failed in the call to 'Join'

I am getting the following error on the word "join" in the code below.
The type of one of the expressions in the join clause is incorrect.
Type inference failed in the call to 'Join'.
var organisationQuery = ClientDBContext.Organisations.Where(x => true);
var orderGrouped = from order in ClientDBContext.Orders.Where(x => true)
group order by order.OrganisationId into grouping
select new { Id = grouping.Key.Value, OrderCount = grouping.Count() };
var orders = from og in orderGrouped
join org in organisationQuery on og.Id equals org.Id
select(x => new OrganisationOrdersReportPoco()
{
OrganisationNameThenCode = org.Name,
TotalOrders = og.OrderCount
});
I don't see a problem with the join clause? Can anyone please advise?
Edit:
This is the piece of SQL I am attempting to write as LINQ.
SELECT grp.OrganisationId,
grp.OrderCount,
organisations.Name
FROM (select OrganisationId,
count(*) as OrderCount
from orders where 1 = 1 group by OrganisationId) grp
LEFT OUTER JOIN organisations on grp.OrganisationId = organisations.OrganisationId
WHERE 1 = 1
I have complicated where clauses on both orders and organisations... simplified for this example.
You are selecting into an anonymous type in the first query:
var orderGrouped = ..
select new { Id = grouping.Key.Value, OrderCount = grouping.Count() };
This 'breaks' the connection with order.
The join looks like it should work for Linq-to-Objects but it can't be converted into SQL.
You'll have to eliminate the anonymous type and somehow make a more direct connection.
I wonder why you don't simply go from Organisations? With a proper mapping using nav-properties it should look like:
from org in ClientDBContext.Organisations
select(x => new OrganisationOrdersReportPoco()
{
OrganisationNameThenCode = org.Name,
TotalOrders = org.Orders.Count
};
using the Id properties should be a little more involved but follow the same pattern.
(Credit to Giorgi Nakeuri)
I was confusing LAMBDA with LINQ expressions.
Replacing my select with this solved it.
select new OrganisationOrdersReportPoco()
{
OrganisationNameThenCode = org.Name,
TotalOrders = og.OrderCount
};

Write sql query to linq

I am having following query in sql :
SELECT [definition],[pos]
FROM [WordNet].[dbo].[synsets]
where synsetid in(SELECT [synsetid] FROM [WordNet].[dbo].[senses]
where wordid = (select [wordid]FROM [WordNet].[dbo].[words]
where lemma = 'searchString'))
I had tried this for sql to linq :
long x = 0;
if (!String.IsNullOrEmpty(searchString))
{
var word = from w in db.words
where w.lemma == searchString
select w.wordId;
x = word.First();
var sence = from s in db.senses
where (s.senseId == x)
select s;
var synset = from syn in db.synsets
where sence.Contains(syn.synsetId)
select syn;
But I am getting following error at sence.Contains()
Error1:Instance argument: cannot convert from
'System.Linq.IQueryable<WordNetFinal.Models.sense>' to
'System.Linq.ParallelQuery<int>'
Below code:
var sence = from s in db.senses
where (s.senseId == x)
select s;
Returns object of type: WordNetFinal.Models.sense, but in where sence.Contains(syn.synsetId) you are trying to search in it syn.synsetId which is an integer.
So you should change above code to:
var sence = from s in db.senses
where (s.senseId == x)
select s.senseId;
x seems to be of Word type, which is not the type of Id (probably int or long).
You're comparing an entire sense row with a synsetId, which is not correct. You're also splitting the original query into two separate queries by using First() which triggers an evaluation of the expression so far. If you can live with not returning an SQL error if there are duplicates in words, you can write the query as something like this;
if (!String.IsNullOrEmpty(searchString))
{
var wordIds = from word in db.words
where word.lemma == searchString
select word.wordId;
var synsetIds = from sense in db.senses
where wordIds.Contains(sense.wordId)
select sense.synsetId;
var result = (from synset in db.synsets
where synsetIds.Contains(synset.synsetId)
select new {synset.definition, synset.pos}).ToList();
}
The ToList() triggering the evaluation once for the entire query.
You could also just do it using a simpler join;
var result = (from synset in db.synsets
join sense in db.senses on synset.synsetId equals sense.synsetId
join word in db.words on sense.wordId equals word.wordId
select new {synset.definition, synset.pos}).ToList();

Converting t-sql query into EF's method syntax

What would be an EF method syntax equivalent for the following TSQL query?
select istb.service_id, ss.service_desc, selected=1
from istb_services istb
inner join setup_services ss on istb.service_id=ss.service_id
where istb.istb_id=3
union
select ss.service_id, ss.service_desc, selected=0
from setup_services ss
where ss.service_id not in (select service_id from istb_services where istb_id=3)
I tried converting the not in part of the query like following:
var _existing = context.istb_services.Where(e => e.istb_id == IstbID);
var _others = context.setup_services.Except(_existing);
but it is generating compile-time error:
The best overloaded method match for 'System.Data.Objects.ObjectQuery.Except(System.Data.Objects.ObjectQuery)' has some invalid arguments
I understand I can't pass different type of ObjectQuery to the .Except method but then what would be the alternative code?
Thanks,
Try the following:
var resultA =
from istb in istb_services
join ss in setup_services on istb.service_id equals ss.service_id
where istb.istb_id == 3
select new { istb.service_id, ss.service_desc, selected = true };
var resultB =
from ss in setup_services
where !istb_services.Any(istb =>
istb.service_id == ss.service_id &&
istb.istb_id == 3)
select new { ss.service_id, ss.service_desc, selected = false };
var result = resultA.Union(resultB);
Anonymous type initializers having identical fields should be compiled to the same anonymous type, making the two sequences compatible for the Union operation.

Categories

Resources