In the following LINQ statement I get the error :
Cannot implicitly convert type 'System.Linq.IQueryable' to 'bool'
The 3rd last line has a blue line under the entire line. Here is the code, I tried various changes, i must be missing something obvious, thanks in advance...
var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
var searchResults = (
from s in allWaste
where
(
from x in _db.WasteIndicatorItems
join y in
_db.WasteIndicators
on x.WasteIndicatorId equals y.WasteIndicatorId
join z in
_db.HazardTypes
on y.HazardTypeId equals z.HazardTypeId
where
s.WasteId == x.WasteId
group new { x, z } by new { x.WasteId, z.Hazardous } into g
select new
{
nbrOf = g.Count(),
g.Key.Hazardous
}
).Where(a => a.nbrOf >= 1 && a.Hazardous == false)
select s
).Distinct();
The problem is you have an IQueryable in your where clause.
Try
...where( (from x in _db.WasteIndicators ... ).Any() )...
Or something that returns a boolean.
Related
Good day. I have a Linq code that when run, shows this error
Invalid length parameter passed to the LEFT or SUBSTRING function.
But when I try to put all the same values into SQL, it works fine. Is there something wrong with my LINQ code?
THE OUTPUT IN SQL
OUTPUT
CODE
var list = (from R in db.vwEtracs_Receipt
join RI in db.vwEtracs_ReceiptItem on R.objid equals RI.parentid
join IA in db.vwEtracs_IncomeAccount on RI.acctid equals IA.objid
join M in db.vwtbl_Motor
on new { motor_no = R.remarks.Substring(5), operator_id = R.payerId }
equals new { motor_no = M.motor_no, operator_id = M.operator_id } into M_join
from M in M_join.DefaultIfEmpty()
join F in db.tbl_Franchise on R.objid equals F.or_id into F_join
from F in F_join.DefaultIfEmpty()
join B in db.tbl_Make on M.brand_id equals B.id
where
IA.objid == "FTFA00000238" &&
R.voidId == null &&
R.remarks != null
orderby R.txndate descending
select new PayedViewModel
{
application_no = F.application_no,
remarks = R.remarks,
serialno = R.serialno,
payername = R.payername,
payeraddress = R.payeraddress,
motor_no = M.motor_no,
chassis_no = M.chassis_no,
plate_no = M.plate_no,
brand_name = B.Make,
motor_id = M.motor_id,
year = R.txndate.Value.Year.ToString(),
mtop = F.mtop,
franchise_id = F.franchise_id
}
).Distinct();
Usually the error shows in this line, motor_no = R.remarks.Substring(5) because when I change it to 4, the code runs smoothly. I tried manually checking all the data in the db but found nothing suspicious nor anything that will give it negative value.
At this point I don't know what is wrong with my code or db. Thank you.
It may happen because your database have string which it's length less than 5
make sure that all R.remarks.length are more than 5
may be you need to do check or something like this :
R.remarks.Length > 5 ? R.remarks.Substring(5) : R.remarks
I'm trying to return a list from a join query and having difficulty with the errors..
here is my code:
public IList<UniStock.Domain.Tables.Inventory> SelectInventoryListByColourSizeGroup(string styleColour, string sizeGroup)
{
var db = new UniStockContext();
IQueryable<Domain.Tables.Inventory> q = (from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select new
{
c
});
return q;
}
Error I'm seeing now is:
Cannot implicitly convert type 'System.Linq.IQueryable' to System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)`
The problem is, as the error says, you cannot return an anonymous type when your method is expecting a specific type. By using the new {} syntax you are creating an anonymous type. Simply remove new {}
public IList<UniStock.Domain.Tables.Inventory> SelectInventoryListByColourSizeGroup(string styleColour, string sizeGroup)
{
var db = new UniStockContext();
IQueryable<Domain.Tables.Inventory> q = (from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select c);
return q.ToList();
}
This part of your LINQ expression
select new { c } ;
Will give you a list of annonymous type objects. Your method signature says it should return an IList<Inventory>. Since you are not returning the expected type, you are getting this compile time error.
You select should be just c which is an alias for db.Inventories ( with the filter though)
var q = from c in db.Inventories
join o in db.SizeGroupSizes
on c.Size.Trim() equals o.Description.Trim()
where (c.SytleColour == styleColour)
&& (o.SizeGroup.Description == sizeGroup)
select c;
return q.ToList();
The variable q will be IQueryable<Inventory> and when you call the ToList() it will execute the LINQ expression and will get a List<Inventory> and you are returning that, which is matching with your method signature (IList<Signature>)
You are projecting into a new AnonymousType by doing this:
select new { c }
What you probably want is to select the object itself like this:
select c
Then you will want to append a .ToList() to the end to execute the query and populate the list.
I have linq query, that left outer join two tables. I found if a value of a field returns null,, then I will get an error message:
"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."
I copied my linq below:
var SrvRef = from s in db.SrvHeads
join r in db.Referrants on s.svhReferrer equals r.refID into r_join
from r in r_join.DefaultIfEmpty()
where s.svhAccID == accId &&
s.svhHeadCnt == HeadId
select new
{
s.svhBalance,
r.refID
};
bool FBeenPaid = SrvRef.FirstOrDefault().svhBalance == 0M; //this causes error
How can I fix this problem?
I'm slightly surprised at the kind of error you're getting, but there are two places you need to take account of the possibility of the result being null:
Within the query, where r can be null. (If you don't want to match when there are no elements in r_join matching s, you shouldn't be using a left outer join)
In the result itself: you're using FirstOrDefault() which will return null if SrvRef is empty.
So at first glance it should probably be something like:
var query = from s in db.SrvHeads
join r in db.Referrants on s.svhReferrer equals r.refID into r_join
from r in r_join.DefaultIfEmpty()
where s.svhAccID == accId && s.svhHeadCnt == HeadId
select new
{
s.svhBalance,
refId = r == null ? 0 : r.refID // Adjust to the appropriate type of refID
};
var result = query.FirstOrDefault();
bool beenPaid = result != null && result.svhBalance == 0m;
With C# 6, you can change the bottom two lines to:
bool beenPaid = query.FirstOrDefault()?.svhBalance == 0m ?? false;
Having said that:
You're not currently using refId in the result anyway - why are you including it in the result?
Are you sure you want a left outer join at all?
Are you sure that taking the first result is really what you want? What if there are multiple results in the join?
Is there any reason you're not doing the whole thing in a query? Something like:
var paid = db.SrvHeads
.Where(s => s.svhAccID == accId && s.svhHeadCnt == HeadId)
.Any(s => db.Refererrants.Any(r => s.svhReferrer == r.refID
&& s.svhBalance == 0m);
.. but just for the precise semantics you want.
I had a similar issue.
Cause: You are using from "r" in r_join.DefaultIfEmpty(). You cannot use same alias name for left outer join.
Solution: Use different alias name if DefaultIfEmpty() cases. Eg: rEmpty
I modified the below query and its working.
var SrvRef = from s in db.SrvHeads
join r in db.Referrants on s.svhReferrer equals r.refID into r_join
from rEmpty in r_join.DefaultIfEmpty()
where s.svhAccID == accId &&
s.svhHeadCnt == HeadId
select new
{
s.svhBalance,
refID = rEmpty == null ? 0 : rEmpty.refID
};
what i think is causing an error is that svhBalance is an int32 value type and you are accessing a null value returned by SrvRef.FirstOrDefault().
please try the following line and let me know if it helped you.
if svhBalance is an int value type
var SrvRefObj= SrvRef.FirstOrDefault(); bool FBeenPaid = (((SrvRefObj!=null)&&(SrvRefObj.svhBalance
!=null))?(SrvRefObj.svhBalance == 0):(false))
else if it's a decimal value type
var SrvRefObj= SrvRef.FirstOrDefault(); bool FBeenPaid = (((SrvRefObj!=null)&&(SrvRefObj.svhBalance
!=null))?(SrvRefObj.svhBalance == 0M):(false))
I have this query that i've been trying to figure out how to convert to LINQ:
select bjbecd, bjbesk, areotx
from insku
inner join iniwre on bjcomp=a7comp and bjbecd=a7becd and bjbesk=a7besk
inner join initem on bjcomp=arcomp and bjbecd=arbecd
where a7comp=1 and
a7wcde in (1,10) and
a7ohdq>0 and rtrim(a7becd) + rtrim(a7besk) not in
(select skucode from eoditems)
And here is my LINQ so far:
(from i in db.INSKUs
join w in db.INIWREs on
new { i.BJCOMP, i.BJBECD, i.BJBESK }
equals
new { w.A7COMP, w.A7BECD, w.A7BESK }
join t in db.INITEMs on
new { i.BJCOMP, i.BJBECD }
equals
new { t.ARCOMP, t.ARBECD }
where w.A7COMP == 1
where w.A7WCDE == 1 || w.A7WCDE == 10
where w.A7OHDQ > 0
where !(from z in db.EODItems
select z.SkuCode).Contains(w.A7BECD.TrimEnd() + w.A7BESK.TrimEnd())
select new { i.BJBECD, i.BJBESK, t.AREOTX }
);
I am getting an error message on the first join stating"The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'."
All searches I did, related to type match errors, but I quadruple checked all my types within the joins, and they are the same.
Try to do something like this :
join w in db.INIWREs on
new { i.BJCOMP, i.BJBECD, i.BJBESK }
equals
new { BJCOMP = w.A7COMP, BJBECD = w.A7BECD, BJBESK = w.A7BESK }
Should work.
I am getting the above mentioned error with this expression:
var aggregate = from t in entities.TraceLines
join m in entities.MethodNames.Where("it.Name LIKE #searchTerm", new ObjectParameter("searchTerm", searchTerm)) on t.MethodHash equals m.MethodHash
where (t.CallTypeId & (int)types) == t.CallTypeId && t.UserSessionProcessId == m_SessionId
group t by m.Name into d
select new
{
d.Key,
d.Sum(x => x.InclusiveDurationMilliseconds) // <- squigglies on this line
};
Any idea what is causing this error?
Do something like:
select new
{
d.Key,
Sum = d.Sum(x => x.InclusiveDurationMilliseconds)
};
It can project a property name from another property, but not from a method....