Getting linq error with group - linq

I am getting the following error when I add the linq grouping.
Error 5 'System.Linq.IGrouping' does not contain a definition for 'Description' and no extension method 'Description' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)
using (var db = new DataContext())
{
var query = from emp in db.Employees
.Where( e=> e.IsDeleted == false && e.DivisionId == divisionId)
from rev in db.Reviews
.Where( r=> r.EmployeeID == emp.EmployeeId && r.IsDeleted == false && r.ReviewPeriodId == reviewPeriodId)
.DefaultIfEmpty()
from obj in db.Objectives
.Where( o=> o.ReviewId == rev.ReviewId && o.IsDeleted == false)
.DefaultIfEmpty()
from objps in db.ObjectiveProgressStatusLanguages
.Where( s=> s.ObjectiveProgressStatusId == obj.ObjectiveProgressStatusId && s.LanguageId == langueageId)
.DefaultIfEmpty()
group objps by new {objps.Description, objps.StatusId into opsgroup
select new
{
Status = opsgroup.Description,
StatusId = opsgroup.StatusId,
Count = opsgroup.Count()
};
return query.CopyToDataTable();

Those fields should be part of the Key. Try changing it to:
select new {
Status = opsgroup.Key.Description,
StatusId = opsgroup.Key.StatusId,
Count = opsgroup.Count()
}

Related

Null reference exception in linq select statement

I am getting a null reference exception from my bellow linq query. I have a table with an entityID(reference to another table to get translated text), but in some case i don't have proper translated text in my child table. This case i need to take lookupName field text and assign to lookupName field.
await _context.FormLookup.Where(x=>!(x.isDeleted))
.Select(x => new LookupList() {
lookupID = x.lookupID,
TransilatedName = _context.TranslatedText.FirstOrDefault(z => z.entityID == x.entityID && z.languageId == language && !(z.isDeleted)).languageText,
lookupName = x.lookupName,
itemCount = x.lookupDetails.Count(),
parent = x.parentID
}).ToListAsync();
I need to add a condition like
TransilatedName = _context.TranslatedText.FirstOrDefault(z => z.entityID == x.entityID && z.languageId == language && !(z.isDeleted)) != null ? TransilatedName = _context.TranslatedText.FirstOrDefault(z => z.entityID == x.entityID && z.languageId == language && !(z.isDeleted)).languageText : x.lookupName,
Any suggestions?
Select property LanguateText before you use FirstOrDefault:
var query = dbContext.FormLookup
.Where(x=>!(x.isDeleted))
.Select(x => new LookupList()
{
lookupID = x.lookupID,
TransilatedName = dbContext.TranslatedText
.Where(translatedText => translatedText.entityID == x.entityID
&& translatedText.languageId == language
&& !translatedText.isDeleted)
.Select(translatedText => translatedText.languageText)
.FirstOrDefault(),
...
});

Left join times out on linq where right table is empty

I have a left join to perform . And take the entire objects from it . However it times out when the item collection is empty on doing .Select (x=>x.object) ;
public Tuple<td_GroupLicense, List<td_UserGroupMap>> ReturnActiveLicenseInfo(int GroupID)
{
Tuple<td_GroupLicense, List<td_UserGroupMap>> Tuple;
#endregion
var GroupUserLicense = from grp in Context.td_Groups
from lic in Context.td_GroupLicenses
.Where(x => grp.IdGroup == x.GroupID && x.GroupID == GroupID)
from ugm in Context.td_UserGroupMaps
.Where(x => grp.IdGroup == x.GroupID && x.GroupID == GroupID)
.DefaultIfEmpty()
select new { GL = lic, UGM = ugm };
td_GroupLicense License = GroupUserLicense.Select(x => x.GL).Distinct().SingleOrDefault();
List<td_UserGroupMap> UserMaps = GroupUserLicense.Select(x => x.UGM)
.OfType<td_UserGroupMap>()
.DefaultIfEmpty().ToList();
Tuple = new Tuple<td_GroupLicense, List<td_UserGroupMap>>(License, UserMaps);
return Tuple;
}
when I do the join then the line in
List<td_UserGroupMap> UserMaps = GroupUserLicense.Select(x => x.UGM)
.OfType<td_UserGroupMap>()
.DefaultIfEmpty().ToList();
times out since the collection UGM in GroupUserLicense is null . It cannot do the operation . I want to put the left join result of License and Usegroupmaps into the corresponding objects . But the Right table is null so the timeout occurs . How to overcome that ? And why is it happening ?

linq to entities if filter parameter is null then select all entities?

Im filtering for entities using an ID but if the ID is null then I want to return all the entities. so in the code below if competitorID is null id like to return all the briefcompetitors.
var competitors =
NeptuneUnitOfWork.Briefs.FindWhere(b => b.ID == briefID)
.Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID)).ToList();
Normally you do it this way:
IQueryable<Brief> briefs = NeptuneUnitOfWork.Briefs.Where(b => b.ID == briefID);
if (competitorID != null)
{
competitors = briefs.Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID));
}
else
{
competitors = briefs.Select(b => b.BriefCompetitors);
}
Technically you could leave the problem to the SQL Server:
// Note the || clause
competitors = briefs.Where(b => b.ID == briefID)
.Select(b => b.BriefCompetitors.Where(b=>b.ID == competitorID || competitorID == null));
Just a minor change to #xanatos post
// Note the || clause
competitors = briefs.Where(b => b.ID == briefID && (competitorID == null || b.ID == competitorID));

NotSupportedException The entity or complex type cannot constructed in a LINQ to Entity query ASP.Net MVC 3

This is the first time i encountered this error .
can someone help me?
public IEnumerable<APPLICANT> GetApplicant()
{
IEnumerable<APPLICANT> applicantdata = Cache.Get("applicants") as IEnumerable<APPLICANT>;
IEnumerable<Profile> profiledata = Cache.Get("profiles") as IEnumerable<Profile>;
if (applicantdata == null)
{
var list = (from f in context.APPLICANTs
select f.APPLICANT_ID).ToList();
var applicantList = (from a in context.Profiles
join app in context.APPLICANTs on a.PROFILE_ID equals app.Profile_id
where list.Contains(app.APPLICANT_ID)
select new APPLICANT());
applicantdata = applicantList.Where(v => v.APPLICANT_LastName != null && v.APPLICANT_LastName != "" ).OrderBy(v => v.APPLICANT_ID).ToList();
if (applicantdata.Any())
{
Cache.Set("applicants", applicantdata, 30);
}
}
And im Having Error in this line
applicantdata = applicantList.Where(v => v.APPLICANT_LastName != null && v.APPLICANT_LastName != "" ).OrderBy(v => v.APPLICANT_ID).ToList();
Thanks if someone will help
change
var applicantList = (from a in context.Profiles
join app in context.APPLICANTs on a.PROFILE_ID equals app.Profile_id
where list.Contains(app.APPLICANT_ID)
select new APPLICANT());
to
var applicantList = (from a in context.Profiles
join app in context.APPLICANTs on a.PROFILE_ID equals app.Profile_id
where list.Contains(app.APPLICANT_ID)
select app);
if you create new APPLICANT() you have newly created applicants without any data
and also applicantList.Where(v => v.APPLICANT_LastName != null && v.APPLICANT_LastName != "" )
can change to
applicantList.Where(v => !String.IsNullOrEmpty(v.APPLICANT_LastName))

Linq: Nested queries are better than joins, but what if you use 2 nested queries?

In her book Entity Framework Julie Lerman recommends using nested queries in preference to joins (scroll back a couple of pages).
In her example see populates 1 field this way, but what id you want to populate 2?
I have an example here where I would prefer to populate the Forename and Surname with the same nested query rather than 2 separate ones. I just need to know the correct syntax to do this.
public static List<RequestInfo> GetRequests(int _employeeId)
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
return db.AnnualLeaveBookeds
.Where(x => x.NextApproverId == _employeeId ||
(x.ApproverId == _employeeId && x.ApprovalDate.HasValue == false))
.Select(y => new RequestInfo
{
AnnualLeaveDate = y.AnnualLeaveDate,
Forename = (
from e in db.Employees
where e.EmployeeId == y.EmployeeId
select e.Forename).FirstOrDefault(),
Surname = (
from e in db.Employees
where e.EmployeeId == y.EmployeeId
select e.Surname).FirstOrDefault(),
RequestDate = y.RequestDate,
CancelRequestDate = y.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
})
.OrderBy(x => x.AnnualLeaveDate)
.ToList();
}
}
There's nothing wrong with your query, but you can write it in a way that is much simpler, without the nested queries:
public static List<RequestInfo> GetRequests(int employeeId)
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
return (
from x in db.AnnualLeaveBookeds
where x.NextApproverId == employeeId ||
(x.ApproverId == employeeId && x.ApprovalDate == null)
orderby x.AnnualLeaveDate
select new RequestInfo
{
AnnualLeaveDate = x.AnnualLeaveDate,
Forename = x.Employee.Forename,
Surname = x.Employee.Surname,
RequestDate = x.RequestDate,
CancelRequestDate = x.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
}).ToList();
}
}
See how I just removed your from e in db.Employees where ... select e.Forename) and simply replaced it with x.Employee.Forename. When your database contains the correct foreign key relationships, the EF designer will successfully generate a model that contain an Employee property on the AnnualLeaveBooked entity. Writing the query like this makes it much more readable.
I hope this helps.
try this
using (SHPContainerEntities db = new SHPContainerEntities())
{
return db.AnnualLeaveBookeds
.Where(x => x.NextApproverId == _employeeId ||
(x.ApproverId == _employeeId && x.ApprovalDate.HasValue == false))
.Select(y =>
{
var emp = db.Emplyees.Where(e => e.EmployeeId == y.EmployeeId);
return new RequestInfo
{
AnnualLeaveDate = y.AnnualLeaveDate,
Forename = emp.Forename,
Surname = emp.Surname,
RequestDate = y.RequestDate,
CancelRequestDate = y.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
};
).OrderBy(x => x.AnnualLeaveDate).ToList();
}

Resources