Comparing a fk_id with id in linq - c#

Want to compare two ids, if they are the same take only these rows and send them so i can print them out.
public IList<tbl_user> getLastc()
{
var fk_id = (from m in dc.tbl_checkins orderby m.checkin_datetime descending select m.fk_user_id).Take(1);
var result = (from c in dc.tbl_users
where c.user_id.Equals(fk_id)
select c).ToList();
/*(from m in dc.tbl_users where m.user_id == fk_id select m).ToList();*/
return result;
}
error:
The comparison operators are not supported for the type
System.Linq.IQueryable1[System.Nullable1[System.Int32]].

In m.user_id == fk_id one of this variables is nullable int, so if you want to compare them do
m.user_id!=null && user_id.Value==fk_id
it will check first if value is not null, then compare it's value with other value. Nullable values have also a property HasValue you can use it to determine if variable has value:
m.user_id.HasValue && user_id.Value==fk_id
note: if fk_id is nullable int change it with m.user_id (error does not say which is nullable int)
EDIT:
this is how it will fit:
(from m in
dc.tbl_users where fk_id.HasValue && fk_id.Value==m.user_id select m).ToList()
EDIT2:
var fk_ids = (from m in dc.tbl_checkins orderby m.checkin_datetime descending select m.fk_user_id).Where(x=>x.HasValue).Select(x=>x.Value);
(from m in
dc.tbl_users where fk_ids.Contains(m.user_id) select m).ToList()

Related

Null value in the result of a left outer join linq causes error

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))

how to add days to datetime by selecting in linq query

I'm trying to select nullable datetime by adding days.
As instance
COMPLETE_TIME = (x.VISIT_DATE.HasValue ? x.VISIT_DATE.Value.AddDays(1) : (DateTime?)null)
If datetime has value i want to add 1 days by selecting query as above.
If datetime does not have value i want to set nullable datetime by selecting query as above.
However if i try above code i get Error (please check bottom side for error)
All Query:
var result=
(from s in context.SURVEYs
join x in context.SURVEY_X on s.SURVEY_ID equals x.SURVEY_ID
join sas in context.SURVEY_ANSWER_SELECTION on s.SURVEY_ID equals sas.SURVEY_ID
join o in context.REP_OPTION on sas.OPTION_ID equals o.OPTION_ID
from PCO in context.REP_PARENT_CHILD_OPTIONS.Where(w => w.CHILD_OPTION_ID == sas.OPTION_ID).DefaultIfEmpty()
where
(s.SURVEY_ID == 5 || s.PARENT_SURVEY_ID == 5) &&
o.SUGGESTION != null &&
PCO.PARENT_OPTION_ID == null
select new
{
SUGGESTION = o.SUGGESTION,
DISPLAY_ORDER = "0",
SUGGESTION_TYPE = o.SUGGESTION_TYPE,
o.EXAMPLE_IMAGE_ID,
COMPLETE_TIME = (x.VISIT_DATE.HasValue ? x.VISIT_DATE.Value.AddDays(1) : (DateTime?)null) // Problem in this part
}).ToList();
Error:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.
Question:
How can i select added datetime or null datetime in select part ?
Any help will be appreciated.
Thanks.
If you are using EF 6 you could use on of the DbFunctions
var result=
(from s in context.SURVEYs
join x in context.SURVEY_X on s.SURVEY_ID equals x.SURVEY_ID
join sas in context.SURVEY_ANSWER_SELECTION on s.SURVEY_ID equals sas.SURVEY_ID
join o in context.REP_OPTION on sas.OPTION_ID equals o.OPTION_ID
from PCO in context.REP_PARENT_CHILD_OPTIONS.Where(w => w.CHILD_OPTION_ID == sas.OPTION_ID).DefaultIfEmpty()
where
(s.SURVEY_ID == 5 || s.PARENT_SURVEY_ID == 5) &&
o.SUGGESTION != null &&
PCO.PARENT_OPTION_ID == null
select new
{
SUGGESTION = o.SUGGESTION,
DISPLAY_ORDER = "0",
SUGGESTION_TYPE = o.SUGGESTION_TYPE,
o.EXAMPLE_IMAGE_ID,
COMPLETE_TIME = (x.VISIT_DATE.HasValue ? Dbfunctions.AddDays(x.VISIT_DATE.value, 1) : (DateTime?)null) // Problem in this part
}).ToList();

LINQ to Entities does not recognize the method 'Int32 ToInt32(Boolean)'

So basically, I am trying to return a set of values to a GridView, which doesn't meet any of the values within an array. However, upon attempting I am getting the error of
LINQ to Entities does not recognize the method 'Int32 ToInt32(Boolean)' method, and this method cannot be translated into a store expression.
Here is my code:
public List<Room> getAvailRoom()
{
//Sessions from Default Page
DateTime checkedIn = Convert.ToDateTime(System.Web.HttpContext.Current.Session["checkIn"]);
DateTime checkedOut = Convert.ToDateTime(System.Web.HttpContext.Current.Session["checkOut"]);
//retrieves all the bookings which happen between two dates
var booking = (from b in context.Booking
where b.departureDate >= checkedIn && b.arrivalDate <= checkedOut
select b);
//Counts how many rooms are booked during those dates
int countRooms = booking.Count();
int[] bookings = new int[countRooms];
foreach (var booktypes in booking)
{
for (int i = 0; i < countRooms; i++)
{
//Addings the RoomIds to the array
bookings[i] = booktypes.RoomId;
}
}
//Returns values that does not equal to any roomIds within the bookings array.
return (from b in context.Room
where b.roomId != Convert.ToInt32(bookings.Any())
select b).ToList();
}
Any ideas what I am doing incorrectly?
You really were looking for a Contains query I think:
return (from b in context.Room
where !bookings.Contains(b.roomId)
select b).ToList();
Two problems with your snippet:
Any() returns a boolean - that's not at all what you want
You are trying to execute Convert.ToInt32 in SQL realm - there's no
equivalent to this there (basically Linq to Entities cannot convert this part to a SQL query), so this can't work.
Note: "bookings.Any()" will return a true or false indicating whether there is any element in the booking array. You are getting this error because you are trying to convert a boolean which is the result of the expression "bookings.Any()" to an integer.
If what you want to do is to get all rooms not booked then i will recommend
if(bookings.Any()){
return (from b in context.Room
where !bookings.contains(b.roomId)
select b).ToList();
}else{
return (from b in context.Room
select b).ToList();
}
meaning: if we have any room booked select those room that are not booked else select all the rooms(since no room is booked)
Note: Pls do your conversion outside link and use your result in your link statement if you need to do type conversion. Since this is C# i don't see you having any issue with type conversion here.
your "bookings[i] = booktypes.RoomId;" should return an array of int which require no conversion i.e "Convert.ToInt32" but if need be for this conversion do it before you i.e
if(bookings.Any()){
var thebooking = new List<int>();
foreach (var booking in bookings)
{
thebooking.Add(Convert.ToInt32(booking));
}
return (from b in context.Room
where !thebooking.contains(b.roomId)
select b).ToList();
}else{
return (from b in context.Room
select b).ToList();
}

Showing Unable to create a constant value of type ''. Only primitive types ('such as Int32, String, and Guid') are supported in this context

I am quering the some tables to get the list of employees based on some conditions using the linq. as
Here class " EmpJobPosition " is from Model.
List<int> empjList=ObjToList(employeeJobPositionIds);
List<EmpJobPosition> empJobPositionList =
(from i in ctx.EmpJobPositions
where empjList.Contains(i.EmpJobPositionId)
select i).ToList<EmpJobPosition>();
var query = (from emp in ctx.Employees
join resg in ctx.Resignations on emp.EmployeeID equals resg.EmployeeID into resglist
from resg in resglist.DefaultIfEmpty()
join jpos in empJobPositionList
on emp.EmployeeID equals jpos.EmployeeId into jposList
from jpos in jposList.DefaultIfEmpty()
(resg == null || resg.HasLeft == false) && emp.CompanyID == 1
select new EmployeesViewModel()).ToList();
But Here while join with empJobPositionList it is showig error like
{"Unable to create a constant value of type 'Etisbew.eOffice.EFModel.EntityModel.EmpJobPosition'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."}
What is the problem here.
You could do something like that (don't try to join an IQueryable on an List)
var query = (
from emp in ctx.Employees
join resg in ctx.Resignations
on emp.EmployeeID equals resg.EmployeeID into resglist
from leftresg in resglist.DefaultIfEmpty()
//put the where clause on EmpJobPositions here
join jpos in ctx.EmpJobPositions.Where(x => empjList.Contains(x.EmpJobPositionId))
on emp.EmployeeID equals jpos.EmployeeId into jposList
from leftjpos in jposList.DefaultIfEmpty()
//don't understand this line, are you missing a where ?
//(leftresg == null || leftresg.HasLeft == false) && emp.CompanyID == 1
select new EmployeesViewModel()).ToList();

How can I fix this LINQ function?

I'm using this code:
var nextLevel = (from p in cd.Objective
where p.Parent_ObjectiveID == null
select p.Level);
And it works, by the moment it returns no elements (because I don't have any element in my database). Although I'd like to know the Top level doing this:
var nextLevel = (from p in cd.Objective
where p.Parent_ObjectiveID == null
select p.Level).Max();
But I get an error:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
Parent_ObjectiveID is a nullable int and level in only int.
Max is looking to return an int because that's the type of p.Level, but forced to return a null (because there are no items in the query). If you cast p.Level to a nullable int, your query should work.
var nextLevel = (from p in cd.Objective
where p.Parent_ObjectiveID == null
select (int?)p.Level).Max();

Categories