I have three tables TableTeam, TableUser and TableLink. I want to join them to get a list.
var teams = _db.TableTeam;
var users = _db.TableUser;
var managerIds = teams.Select(x=>x.ManagerId).ToList();
var list = (from user in _db.TableUser
where user.EndDate == null && user.ManagerId != null && managerIds.Contains(user.ManagerId.Value)
let r = _db.TableLink.FirstOrDefault(l => l.ProjectId == projectId && l.UserId == user.UserId)
let t = _db.TableTeam.FirstOrDefault(m => m.ManagerId == user.ManagerId)
select new MyDto
{
ProjectId = projectId,
UserId = user.UserId,
IsAssigned = r.AssignedId > 0 ?true : false,
AssignedId = r.AssignedId,
Percent = r.Percent.HasValue ? (r.Percent.Value).ToString() + "%": ""
}).GroupBy(d => d.UserId).ToList();
For the table TableLink, the corresponding dataSet class in entity framework is:
public LinkDto
{
public int AssignedId {get;set;}
public short ProjectId {get;set;}
public short UserId {get;set;}
public decimal? Percent {get;set;}
// ...
}
However I got the error:
Nullable object must have a value
I think that it may be caused by decimal? Percent. But not sure how to fix it. Also I can use the store d procedure as well, which means if you can solve it by SQL query, that is also great.
It turns out I have to move let codes before where clause then add the condition to where.
Such as
var list = (from user in _db.TableUser
let r = _db.TableLink.FirstOrDefault(l => l.ProjectId == projectId && l.UserId == user.UserId)
let t = _db.TableTeam.FirstOrDefault(m => m.ManagerId == user.ManagerId)
where user.EndDate == null && user.ManagerId != null && managerIds.Contains(user.ManagerId.Value)
&& r != null && t != null
select new MyDto
{
ProjectId = projectId,
UserId = user.UserId,
IsAssigned = r.AssignedId > 0 ?true : false,
AssignedId = r.AssignedId,
Percent = r.Percent.HasValue ? (r.Percent.Value).ToString() + "%": ""
}).GroupBy(d => d.UserId).ToList();
Related
What will be the proper linq syntax of below SQL Query ?
select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2
Problem I faced:
I required to filter Where Condition two times 1st at the time within the join & 2nd time during the object.Select expression, please check bellow
var results = (from a in appointments
join ad in _appointmentDetailRepository.GetAll() on a.ID equals ad.AppointmentID
where ad.ApprovalStatusID == 2
&& DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
&& DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
orderby a.ID
select new Appointment
{
ID = a.ID,
CompanyID = a.CompanyID,
LocationID = a.LocationID,
AppointmentDetail = a.AppointmentDetail.Select(ad => new AppointmentDetail
{
ID = ad.ID,
AppDateFrom = ad.AppDateFrom,
AppDateTo = ad.AppDateTo,
AppointmentStatusID = ad.AppointmentStatusID,
}).Where(ad=> ad.ApprovalStatusID == 2
&& DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
&& DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)).ToList()
}).GroupBy(x => x.ID).Select(x => x.DefaultIfEmpty().FirstOrDefault());
Query : Why I required to write Where clause 2 times ?
Required Result
An Appointment Object --> Containing ICollection<AppoinmentDetails> if Details.Where Condition == True
From what I see (without knowing the model you have), it looks like you should use the already joined and filtered Details from ad instead of looking it up again from the Property a.AppointmentDetail...
Untested:
select new Appointment
{
ID = a.ID,
CompanyID = a.CompanyID,
LocationID = a.LocationID,
AppointmentDetail = ad.ToList(), // <-- don't you think?
...
}
For the given SQL query
select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2
LINQ query can be written as
var results = (from a in appointments
join ad in appointmentDetails on a.ID equals ad.AppointmentID
where ad.ApprovalStatusID == 2
&& a.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
&& a.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t"
&& ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
&& ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
select new
{
ID = a.ID,
AppointmentStatusID = a.AppointmentStatusID,
DetailID = ad.ID
}).ToList();
You can also write it like
var results = appointmentDetails
.Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
&& ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
&& ad.ApprovalStatusID == 2
&& ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
&& ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
.Select(ad =>
new
{
ID = ad.Appointment.ID,
AppointmentStatusID = ad.Appointment.AppointmentStatusID,
DetailID = ad.ID
})
.ToList()
As per the updated question, to get the the Appointment object with a collection of AppointmentDetails, please try this query
var results = appointmentDetails
.Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
&& ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
&& ad.ApprovalStatusID == 2
&& ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
&& ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
.Select(ad =>
new
{
ID = ad.Appointment.ID,
AppointmentStatusID = ad.Appointment.AppointmentStatusID,
Detail = ad
})
.AsEnumerable()
.GroupBy(a => new { a.ID, a.AppointmentStatusID })
.Select(a => new Appointment
{
ID = a.Key.ID,
AppointmentStatusID = a.Key.AppointmentStatusID,
AppointmentDetails = a.Select(d => d.Detail).ToList()
})
.ToList();
I have two datatables,
var userList1 = from myRow in dt.AsEnumerable()
where myRow.Field<bool?>("IsActive1") == null
? true
: myRow.Field<bool?>("IsActive1") == true
select myRow;
var userList2 = from myRow in dt1.AsEnumerable()
select myRow;
dt1 table shows like this,
Using this Linq query,
var objUserSetUp1 = (from A in userList1
join B in userList2
on new
{
UserId = A.Field<Int64?>("Id") == null
? 0
: A.Field<Int64>("Id")
}
equals new
{
UserId = B.Field<Int64?>("UserId") == null
? 0
: B.Field<Int64>("UserId")
}
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = B.Field<Int64>("docCount")
}).ToList();
How can I get if UserId is null also want to take docCout field value too. How can I do this inside the query?
I think you need a Left Outer Join, where the default value for the outer join (ie when no matching record exists) is the userList2 entry where Field("UserId") is null.
See below (untested, but you get the idea!):
var objUserSetUp1 = (from A in userList1
join B in userList2
on A.Field<Int64?>("Id") equals B.Field<Int64?>("UserId")
into BGroup
from C in BGroup.DefaultIfEmpty(userList2.Single(u => u.Field<Int64?>("UserId") == null))
select new
{
UserId = A.Field<Int64>("Id"),
FirstName = A.Field<string>("FirstName"),
SurName = A.Field<string>("SurName"),
Computer_Name = A.Field<string>("Computer_Name"),
IP_Address = A.Field<string>("IP_Address"),
LogInTime = A.Field<string>("LogInTime") == null
? "UnKnown"
: A.Field<string>("LogInTime"),
UserName = A.Field<string>("UserName"),
Password = A.Field<string>("Password"),
login_Id = A.Field<Int64?>("login_Id") == null
? 0 :
A.Field<Int64?>("login_Id"),
docCount = C.Field<Int64>("docCount")
}).ToList();
I want to, in the midst of a linq to sql query where clause, check against a public int. I am getting this error: Method 'Int32 isInDept(System.String)' has no supported translation to SQL.
Vaguely related classes (from a public static class called ad):
//get AD property
public static string GetProperty(this Principal principal, String property) {
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
if (directoryEntry.Properties.Contains(property))
return directoryEntry.Properties[property].Value.ToString();
else
return String.Empty;
}
public static string GetDepartment(this Principal principal) {
return principal.GetProperty("department");
}
The Classes in question (from a different class):
public int isInDept(string department) {
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(domain, GetUserId());
if (department == userPrincipal.GetDepartment()) {
return 3;
}
else { return 2; }
}
public intranetGS.viewArticle viewArticle(int id) {
string user = GetUserId();
var result = ( from a in n.articles
join s in n.sections on a.section equals s.section_id
join p in n.privacies on a.privacy equals p.privacy_id
let iid = isInDept(s.name)
where (a.active == true && a.article_id == id && a.privacy < iid) ||
(a.active == true && a.article_id == id && a.privacy == 3 && a.author == user)
select new intranetGS.viewArticle {
articleId = a.article_id,
title = a.title,
author = a.author,
html = a.html,
section = s.name,
privacy = p.name,
dateCreated = a.date_created,
dateModified = a.date_modified,
userCreated = a.user_created,
userModified = a.user_modified
}).First();
var nv = (from v in n.navs
join s in n.sections on v.section equals s.section_id
let iid = isInDept(s.name)
where (v.active == true && s.name == result.section && v.privacy < 3) ||
(v.active == true && s.name == result.section && v.privacy == iid && v.user_created == user)
select v.html);
StringBuilder sb = new StringBuilder();
foreach (var r in nv) {
sb.Append(nv);
}
result.articleNav = sb.ToString();
return result;
}
What am I doing wrong? If I can't do it this way, how is it suggested that it be done?
It is not possible to translate that function to SQL, one workaround for this is to make most of your query with linq to sql, and use Linq to Objects for the rest. It should be something like this:
var query = ( from a in n.articles
join s in n.sections on a.section equals s.section_id
join p in n.privacies on a.privacy equals p.privacy_id
where (a.active == true && a.article_id == id)
select new intranetGS.viewArticle {
articleId = a.article_id,
title = a.title,
author = a.author,
html = a.html,
section = s.name,
privacy = p.name,
privacyId = a.privacy,
dateCreated = a.date_created,
dateModified = a.date_modified,
userCreated = a.user_created,
userModified = a.user_modified
}).ToList();
And then filter the list:
var result = query.Where(a => (a.privacyId < isInDept(a.section)) ||
(a.privacyId == 3 && a.author == user)).First();
Then you can do the same for the second query.
I have this LINQ to Entity query which fetches around 5000 Plus records. I have been noticed is that the higher the records returned the more time it takes to execute the query and return the results.
lstUserAssignments = context.UserAssessments.Where(a=>a.UserID == UserID && a.CourseID == ClassID && a.ProductID == a.ProductID && a.AppID == ApplicationID && a.IsDeleted == false && a.Score_Percentage >= 0).Select(a=> new UserAssessmentEntity()
{
ApplicationID = a.AppID,
AttemptNo = a.AttemptNo,
CourseID = a.CourseID,
Score_Percentage = (float)(a.Score_Percentage != null ? a.Score_Percentage : 0),
Status = a.Status,
UserAssessmentID = a.UserAssessmentID,
UserID = a.UserID,
UserScore = a.User_Score,
CreatedDateTime = a.CreatedDateTime,
ModifiedDateTime = a.ModifiedDateTime,
TimeSpent=a.UserAssessmentDetails.Sum(i=>i.TimeSpent??0),
InstructorFeedbackText = a.UserAssessmentDetails.FirstOrDefault()!=null?a.UserAssessmentDetails.FirstOrDefault().InstructorFeedbackText:string.Empty
}).ToList();
To make the query simple. There is UserAssessment and UserAssessmentDetails table. The first one is the parent and the latter the child. There is some performance issue in the query and i feel its in calculating TimeSpent and InstructorFeedback.
Can anyone point my finger on the problem.
Take and Skip:
context.UserAssessments.Where(a=>a.UserID == UserID && a.CourseID == ClassID && a.ProductID == a.ProductID && a.AppID == ApplicationID && a.IsDeleted == false && a.Score_Percentage >= 0).Select(a=> new UserAssessmentEntity()
{
ApplicationID = a.AppID,
AttemptNo = a.AttemptNo,
CourseID = a.CourseID,
Score_Percentage = (float)(a.Score_Percentage != null ? a.Score_Percentage : 0),
Status = a.Status,
UserAssessmentID = a.UserAssessmentID,
UserID = a.UserID,
UserScore = a.User_Score,
CreatedDateTime = a.CreatedDateTime,
ModifiedDateTime = a.ModifiedDateTime,
TimeSpent=a.UserAssessmentDetails.Sum(i=>i.TimeSpent??0),
InstructorFeedbackText = a.UserAssessmentDetails.FirstOrDefault()!=null?a.UserAssessmentDetails.FirstOrDefault().InstructorFeedbackText:string.Empty
}).Take(10).Skip(10).ToList();
On our online billing application, we give a billing summary of what bills the customer received and the payments they made.
In order for this to work, I have to first pull the payments then match them to the bills. So I have do something like:
foreach (BillPaymentSummary payment in billPayments)
{
DateTime dt = payment.DueDate;
// Debug errors on this next line
var summary = (from a in db.BillHistories
where a.CustomerId == customerNumber && a.DueDate == dt && a.Type == "BILL"
select new BillSummary
{
Id = a.Id,
CustomerId = a.CustomerId,
DueDate = a.DueDate,
PreviousBalance = a.PreviousBalance.Value,
TotalBill = a.TotalBill.Value,
Type = a.Type,
IsFinalBill = a.IsFinalBill
}).SingleOrDefault();
if (summary != null)
{
summary.PayDate = payment.PaidDate;
summary.AmountPaid = payment.AmountPaid;
returnSummaries.Add(summary);
}
else
{
summary = (from a in db.BillHistories
where a.CustomerId == customerNumber && a.DueDate == payment.DueDate && a.Type == "ADJ "
select new BillSummary
{
Id = a.Id,
CustomerId = a.CustomerId,
DueDate = a.DueDate,
PreviousBalance = a.PreviousBalance.Value,
TotalBill = a.TotalBill.Value,
Type = a.Type,
IsFinalBill = a.IsFinalBill
}).SingleOrDefault();
if (summary != null)
{
summary.PayDate = payment.PaidDate;
summary.AmountPaid = payment.AmountPaid;
returnSummaries.Add(summary);
}
}
}
I have been playing with this, but no matter what I do, I get the following error message:
The entity or complex type 'UtilityBill.Domain.Concrete.BillSummary' cannot be constructed in a LINQ to Entities query.
Is it because I am running queries within queries? How can I get around this error?
I have tried searching Google for an answer and see many answers, but none of them seem to explain my problem.
You cannot project onto a mapped entity. You would have to call ToList() before doing your mapping.
Or better yet, change to the following (calling FirstOrDefault will execute the query and allow you to populate your object):
var summary = db.BillHistories.FirstOrDefault(a => a.CustomerId == customerNumber && a.DueDate == dt && a.Type == "BILL").Select(x => new BillSummary
{
Id = a.Id,
CustomerId = a.CustomerId,
DueDate = a.DueDate,
PreviousBalance = a.PreviousBalance.Value,
TotalBill = a.TotalBill.Value,
Type = a.Type,
IsFinalBill = a.IsFinalBill
});
To decouple yourself from the Entity Framework you may want to also consider using a different model class to return instead of the Entity Framework model.
What I ended up doing was:
foreach (BillPaymentSummary payment in billPayments)
{
var data = db.BillHistories.Where(b => b.CustomerId == customerNumber && b.DueDate == payment.DueDate && b.Type == "B").FirstOrDefault();
if (data != null) // There is a bill history
{
returnSummaries.Add(new BillSummary
{
Id = data.Id,
CustomerId = data.CustomerId,
DueDate = data.DueDate,
PreviousBalance = data.PreviousBalance,
TotalBill = data.TotalBill,
Type = (data.Type.Trim() == "B" ? "BILL" : (data.Type == "A" ? "ADJ" : "")),
IsFinalBill = data.IsFinalBill,
PayDate = payment.PaidDate,
AmountPaid = payment.AmountPaid
});
}
else // No bill history record, look for an adjustment
{
data = db.BillHistories.FirstOrDefault(b => b.CustomerId == customerNumber && b.DueDate == payment.DueDate && b.Type == "A");
if (data != null)
{
returnSummaries.Add(new BillSummary
{
Id = data.Id,
CustomerId = data.CustomerId,
DueDate = data.DueDate,
PreviousBalance = data.PreviousBalance,
TotalBill = data.TotalBill,
Type = (data.Type.Trim() == "B" ? "BILL" : (data.Type == "A" ? "ADJ" : "")),
IsFinalBill = data.IsFinalBill,
PayDate = payment.PaidDate,
AmountPaid = payment.AmountPaid
});
}
}
db.SaveChanges();
}