Linq to entities where condition not working - entity-framework

var records = (from m in ctx.myData
from StatusReport in ctx.ReportStatusDetails
where (m.UserId == user.UserId &&
StatusReport.StatusId == 1 &&
ctx.Report.Any(r => r.ReportDate.Month == SqlFunctions.GetDate().Value.Month &&
r.ReportDate.Year == SqlFunctions.GetDate().Value.Year))
select new
{
m.Id,
m.Company.CompanyName,
m.UserId,
m.aspnet_Membership.aspnet_Users.UserName,
m.aspnet_Membership.Email
})
.Distinct()
.ToList();
The where condition StatusReport.StatusId == 1 is not working. The query is returning even rows where StatusReport.StatusId is not equal to 1.
Why is this condition being ignored?

Because you did not joined/related StatusReport with m. And result contains only m. See example http://msdn.microsoft.com/en-us/library/bb311040.aspx

Related

Can't Get Count of More than one table fields Through Linq Query

My Aggregate Query
var attendanceAggregate = (from ed in _context.EmployeeDetail
join uf in _context.userInfo on ed.employeeCode equals uf.SSN
join ct in _context.EmployeeContract on ed.employeeCode equals ct.EmployeeCode
join chio in _context.checkinout on uf.USERID equals chio.USERID
join vlr in _context.LeaveRequest.Where(v => v.VerifiedByHR != null)
.Where(s => s.RequestDate >= FromDate && s.RequestDate <= ToDate)
on ct.ContractID equals vlr.ContractID into vlri
from vlr in vlri.DefaultIfEmpty()
join tlr in _context.LeaveRequest.Where(v => v.ApprovedBy != null && v.RequestedBy != null && v.RejectedBy == null)
.Where(s => s.RequestDate >= FromDate && s.RequestDate <= ToDate)
on ct.ContractID equals tlr.ContractID into tlri
from tlr in tlri.DefaultIfEmpty()
where uf.USERID == chio.USERID && chio.CHECKTIME != null
&& chio.CHECKTIME >= FromDate && chio.CHECKTIME <= ToDate
group new { ed, chio, ct, vlr, tlr } by new
{
ed.employeeCode,
ed.name,
ed.surName,
ed.nameDari,
ed.surNameDari
} into g
select new
{
g.Key.name,
//fullName = _culture.GetLanguageId() == 1 ? g.Key.name + ' ' + g.Key.surName : g.Key.nameDari + ' ' +
g.Key.surNameDari,
code = g.Key.employeeCode,
TotalPendingRequest=g.Count(s=> s.tlr.LeaveRequestID != null)
}).ToList();
and error that occured to me
'.Count(s => (Nullable)s.tlr.LeaveRequestID != null)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
This question needs details about EF Core version. EF Core 5 can translate this query but not earlier versions. But there is workaround using Sum
...
select new
{
g.Key.name,
g.Key.surNameDari,
code = g.Key.employeeCode,
TotalPendingRequest = g.Sum(s => s.tlr.LeaveRequestID != null ? 1 : 0)
}

Optional compare in query

Hi i have a problem with my query because i want select that items which brands are called in string subcategory. But if that subcategory is equal "none" i would to select them all i want to do it in query not in linq. Here's my function
string subcategory = HttpContext.Current.Session["subcategory"].ToString() == "none" ? "" : HttpContext.Current.Session["subcategory"].ToString();
List<int> processors = (from x in context.Processors
where (x.Price >= filters.PriceMin && x.Price <= filters.PriceMax)
where x.Brand == subcategory
select x.Product_ID).ToList();
The pattern for this in LINQ and EF is to build up the query differently for the two cases before the query is executed by calling IQueryable.ToList(); eg:
string subcategory = ...;
var q = from x in context.Processors
where (x.Price >= filters.PriceMin && x.Price <= filters.PriceMax)
select x;
if (subcategory != "none")
{
q=q.Where(x => x.Brand == subcategory);
}
var processors = q.Select(x => x.Product_ID).ToList();

EF Conditional Query to match with whatever information available doesn't work

I am trying to write a query to search employees by whatever of the 3 attributes are available in my object using Linq to Entity.
My object has First name, Last name, and Date of Birth.
My query looks like this (search is the object containing partial or full info)
var results = ctx
.emp
.Where(p =>
p.Fname == (search.Firstname ?? p.Fname)
&& p.Lname == (search.Lastname ?? p.Lname)
&& p.Dob == (search.Dob ?? p.Dob ))
The issue is that above query is matching employees with null values in each of those 3 columns along with the matching value. For instance if I provide search.Firstname to be John, it matches everyone with first name John AND everyone with null in first name.
How do I not match nulls in fields where a value is provided?
Haven't tested, but won't something like this work.
var results = ctx
.emp
.Where(p => (search.Firstname == null ? p.Fname == p.Fname : p.Fname == search.Firstname) ||
(search.Lastname == null ? p.Lname == p.Lname : p.Lname == search.Lastname) ||
(search.Dob == null ? p.Dob == p.Dob : p.Dob == search.Dob))
Please excuse the formatting. Using my mobile :)

Conditional WHERE clause on an Entity Framework context

objRecord = await _context.Persons
.Where(tbl => tbl.DeletedFlag == false)
.ToListAsync();
This is the EF code I've got which successfully gets all the records from the Person table where DeletedFlag is false.
I want to add another where criteria that if a surname has been passed in, then add the extra where clause
.Where(tbl => tbl.Surname.Contains(theSurname))
I've tried IQueryable and some other options but can't figure out how to do the equivalent of
string theSurname = "";
objRecord = await _context.Persons
.Where(tbl => tbl.DeletedFlag == false)
if ( theSurname != "") {
.Where(tbl => tbl.Surname.Contains(theSurname))
}
.ToListAsync();
which obviously doesn't work as you can't put an if statement in an EF call.
I can add a criteria afterwards that limits objRecord, but I don't want to retrieve all the records, then cut it down, I'd rather only get the records I need.
You can combine conditions in the Where method by just adding tbl.Surname.Contains(theSurname) so your final query will look like below:
objRecord = await _context.Persons
.Where(tbl => tbl.DeletedFlag == false &&
tbl.Surname.Contains(theSurname))
.ToListAsync();
You have to apply logical AND (&&) with the existing condition in Where clause i.e. tbl.Surname.Contains(theSurname);
So your query would be
.Where(tbl => tbl.DeletedFlag == false && tbl.Surname.Contains(theSurname));

How to filter the OrderBy

i am retrieving data from database on the base of there id, as can be seen,
public ActionResult loadEpisodes(int id, string name, int epId)
{
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderByDescending(c => c.Sequence);
//some other code removed for the ease
return view();
}
It will return the episodes of some 'id' and in descending sequence value.
My question is, if there is way to retrieve the data in descending order but order must starts from the episode id 'epId'
I have tried the above method but failed
ViewBag.LoadEps = db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true)
.OrderBy(c=>c.Sequence)
.First(c=> c.VideoEpisodeId ==epId);
EDIT: If I understand the problem correctly, you want the order to be a given episode with Id epId first, then a list ordered by sequence.
I'm not sure it can be done in one Linq query.
How about creating a new list, putting your chosen VideoEpisode in as the first element, and then appending a sorted list of the other episodes after that. Something like:
var Loadeps = new List<VideoEpisode>();
Loadeps.Add(db.VideoEpisode.First(c=> c.VideoEpisodeId ==epId));
Loadeps.Add(db.VideoEpisode
.Where(ve => ve.VideoId == id && ve.IsActive == true && c.VideoEpisodeId != epId)
.OrderByDescending(c => c.Sequence)).toList();