Get Date part Using LINQ - linq

I have four tables, with Date data type for the fields startingDate, EndingDate, and ApplyingDate.
I am using ADO.net Entity Framework.
I have written the following query to get the results, but I am getting the dates with the time, and I want only the date part.
I have used EntityFunctions.TuncateTime, but I am still getting same results.
Could anyone please suggest me, how to Get the date only ?
var leaveList = (from application in db.tbl_ApplicationData
join employee in db.tbl_EmployeeDetails
on application.UserName equals employee.UserName
join leaveType in db.tbl_LeaveType
on application.LeaveTypeId equals leaveType.LeaveTypeId
join status in db.tbl_Status
on application.ApplicationStatusId equals status.StatusId
where application.UserName == "100083"
select new
{
EmployeeName = employee.EmployeeName,
LeaveTypeID = leaveType.LeaveTypeName,
StartingDate = EntityFunctions.TruncateTime(application.StartingDate),
EndingDate = EntityFunctions.TruncateTime(application.EndingDate),
AppliedDate = EntityFunctions.TruncateTime(application.ApplyingDate),
NoOfDays = application.NoOfDays,
LeavePurpose = application.LeavePurpose,
LeaveStatus = status.StatusName
});

If your entity model is a System.DateTime, you can just use the DateTime methods when you are using your object:
select new {
EndingDate = application.EndingDate
};
var myValue = leaveList.EndingDate.Date;
Or if you want a string:
leaveList.EndingDate.ToShortDateString()

Related

Group by with count on multiple table in LINQ

Sql query to LINQ: Both are pasted over here, getting issue in LINQ - need suggestion:
select bm.MachineId,al.AlarmId,am.AlarmName, count(al.AlarmId)AlarmCount
from BatchMachineWise bm
join AlarmLog al on bm.MachineId = al.MachineId
join Alarm am on am.AlarmId = al.AlarmId
where bm.BatchId = 12476
group by bm.MachineId,al.AlarmId,am.AlarmName
GroupBy returns IGrouping<TKey,TElement> interface which has Key property which should be used to access fields used for grouping:
select new AlarmSummary
{
MachineId = gr.Key.MachineId,
AlarmId = gr.Key.AlarmId,
AlarmName = gr.Key.AlarmName
....
}

LINQ Error when using multiple JOIN in same statement on CRM 2011 Plug-in

Hi I am trying to join multiple entities in CRM 2011 but I get and error saying: {"'xrmsm_sessionEnrollments' entity doesn't contain attribute with Name = 'xrmsm_termsid'."}. That is correct but I am joining the entity that have that attribute.
My Linq Query:
var query2 = from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup)
&& e.xrmsm_YearLookup.Equals(entity.GetAttributeValue("xrmsm_studentlookup"))
&& ic.xrmsm_institutionCoursesId == institutionCourseGuid
&& t.xrmsm_termsId == termGuid)
select new { sessionName = s.xrmsm_sessionsName, StudentName = e.xrmsm_studentsName, StudentId = e.xrmsm_StudentLookup.Name };
My original SQL query that works on SQL Server:
SELECT en.xrmsm_currentsessionenrollmentsname
,en.xrmsm_isreadonlyname
,en.xrmsm_sessionenrollmentsaverage
,en.xrmsm_sessionenrollmentsgrade
,en.xrmsm_sessionenrollmentsid
,en.xrmsm_sessionenrollments_id
,en.xrmsm_sessionlookup as sessionid
,en.xrmsm_sessionlookupname
,en.xrmsm_sessionsname
,en.xrmsm_studentlookup AS studentid
,en.xrmsm_studentlookupname
,en.xrmsm_studentsname
,en.xrmsm_termsessionlookup
,en.xrmsm_termsessionlookupname
,en.xrmsm_withdrawal
,en.xrmsm_yearaverage
,en.xrmsm_yeargrade
,en.xrmsm_yearlookup
,en.xrmsm_yearlookupname
FROM CoseyTest_MSCRM.dbo.Filteredxrmsm_sessionEnrollments as en INNER JOIN
CoseyTest_MSCRM.dbo.Filteredxrmsm_sessions crmsessions ON
(en.xrmsm_sessionlookup = crmsessions.xrmsm_sessionsid AND en.xrmsm_yearlookup = crmsessions.xrmsm_yearlookup)
INNER JOIN Filteredxrmsm_institutionCourses institutionCourses
on crmsessions.xrmsm_institutioncourselookup = institutionCourses.xrmsm_institutioncoursesid
Inner Join Filteredxrmsm_term_sessions as termsession
on en.xrmsm_termsessionlookup = termsession.xrmsm_term_sessionsid
Inner Join Filteredxrmsm_terms as terms
on termsession.xrmsm_termlookup = terms.xrmsm_termsid
where en.xrmsm_yearlookup = '4BA07BED-3F51-E211-8359-00155D004403'
and en.xrmsm_studentlookup = 'C844AF65-5B51-E211-8359-00155D004403'
and terms.xrmsm_termsid = 'D1D107B7-4551-E211-8359-00155D004403'
and institutionCourses.xrmsm_institutioncoursesid = '2121914E-4551-E211-8359-00155D004403'
Linq provider for CRM has some limitations. You can fount it here. Check if your query violates limitations.
Try having a look at the actual query that it is generating and run that in SQL, it may help understand what is going on.
It could be that something your doing in LINQ is not available in CRM as paramosh mentioned but I can't see anything that jumps out at me.
Thanks for all your responses. I did the following workaround.
Make a query that retrieve a list of all the Student enrollments
Use the Find method of the List<T> class to find if a record exist with the conditions I am searching for.
var query2 = (from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup))
select new
{
EnrollmentId = e.xrmsm_sessionEnrollments_id,
SessionId = s.xrmsm_sessions_id,
EnrollmentYear = e.xrmsm_YearLookup,
InstitutionCourseId = (Guid)ic.xrmsm_institutionCoursesId,
TermId = (Guid)t.xrmsm_termsId,
Student = e.xrmsm_StudentLookup
}).ToList();
var q = query2.Find(r => r.EnrollmentYear.Id == entity.GetAttributeValue<EntityReference>("xrmsm_yearlookup").Id
&& r.InstitutionCourseId == institutionCourseGuid
&& r.TermId == termGuid);

need to return the first record linq

I need to return only the first record. Although I had to put the z.FirstOrDefault(); still more than one were displayed
public DataTable GetDependents(string EmployeeID)
{
HealthCareSystem.DataClassesDataContext db = new HealthCareSystem.DataClassesDataContext();
var z = (from s in db.SelectingDependentsGroupBies
where s.EmployeeID.Equals(EmployeeID)
join d in db.Dependents on s.DependentID equals d.DependentID
orderby s.DependentID descending
//Selecting wanted tables dependents fields by datatable
select new DependentsX { DependentID = Convert.ToInt32(s.DependentID), EmployeeID = s.EmployeeID, Name = s.Name, Surname = s.Surname, IDCardNo = s.IDCardNo, ContactNo = s.ContactNo, BirthDate = s.BirthDate, StartSchemeDate = s.StartDate, EndSchemeDate = s.EndDate, RelationType = s.Type, Payment = Convert.ToDouble(d.Payment), });
var firstRecord = z.FirstOrDefault();
Add this line after your existing code:
var firstRecord = x.First();
If there might be zero results and you don't want an exception then you can use FirstOrDefault instead.
var firstRecord = x.FirstOrDefault();
Another common way is to enclose your query in parenthesis and then include the extension methods outside the parenthesis:
var x = (from d in db.DependentsRelationsViews
where d.IDCardNo.Equals(DepID)
orderby d.DependentID descending
select new DependentsX
{
DependentID = Convert.ToInt32(d.DependentID),
EmployeeID = d.EmployeeID,
Name = d.Name,
Surname = d.Surname,
IDCardNo = d.IDCardNo,
ContactNo = d.ContactNo,
BirthDate = d.BirthDate,
StartSchemeDate = Convert.ToDateTime(d.StartSchemeDate),
EndSchemeDate = d.EndSchemeDate,
Payment = d.Payment,
RelationType = Convert.ToString(d.Type)
}).FirstOrDefault();
If you don't enclose it in parenthesis and try to call FirstOrDefault() then you're applying that extension to the anonymous type in just the very last Select clause. By enclosing the whole query in parenthesis and then calling the FirstOrDefault() extension, you're indicating to the compiler that you wish to apply it to the return value of your entire query, which will be the IEnumerable<> or IQueryable<> collection.

Grouping in LINQ to Entity Model

I have following fields in entity model object
MONTH_CHAR char(1)
AVG_BALANCE int
PROD_CAT_ID int
FLG_PERS_COMM chat(1)
ACCOUNT_COUNT int
I want group by MONTH_CHAR column, I 'll write following SQL Query for this
SELECT MONTH_CHAR,
SUM(AVG_BALANCE) AS AVG_BALANCE,
MAX(PROD_CAT_ID) AS PROD_CAT_ID,
MAX(ACCOUNT_COUNT) AS ACCOUNT_COUNT,
FROM contactSummary
WHERE PROD_CAT_ID = 1
GROUP BY MONTH_CHAR
I want this query to be converted to LINQ Query.
Thanks in advance
from contact in context.Contacts
group contact by contact.Month_Char into g
select new
{
MonthChar = g.Key,
AvgBalance = g.Average(x=>x.Avg_Balance)
CatID = g.Max(x=>x.Prod_Cat_ID)
AccountCount = g.Max(x=>x.Account_Count)
}

Binding LINQ query to DataGridView

This is very confusing, I use AsDataView to bind query result to a dgv and it works fine with the following:
var query = from c in myDatabaseDataSet.Diamond where c.p_Id == p_Id select c;
dataGridView1.DataSource = query.AsDataView();
However, this one results in an Error:
var query = from item in myDatabaseDataSet.Items
where item.p_Id == p_Id
join diamond in myDatabaseDataSet.Diamond
on item.p_Id equals diamond.p_Id
join category in myDatabaseDataSet.DiamondCategory
on diamond.dc_Id equals category.dc_Id
select new
{
Product = item.p_Name,
Weight = diamond.d_Weight,
Category = category.dc_Name
};
dataGridView1.DataSource = query.AsDataView();
Error:
Instance argument: cannot convert from
'System.Collections.Generic.IEnumerable<AnonymousType#1>' to
'System.Data.DataTable'
AsDataView doesn't show up in query.(List). Why is this happen? How to bind the query above to the dgv then?.
The signature of the AsDataView is as follows:
public static DataView AsDataView(
this DataTable table
)
The only parameter is the DataTable.
The query you have is returning an IEnumerable of an anonymous type which doesn't have an implicit conversion to a DataTable (or a sequence of DataRow instances, in which case you could use that to help you create a DataTable).
You need to get the results back into a DataTable or something you can convert into a DataTable and then it will work.
In your particular case, it seems that you were (or are) using typed DataSets. If that is the case, then you should be able to take the values that were selected and then create new typed DataRow instances (there should be factory methods for you) which can then be put into a typed DataTable, which AsDataView can be called on.
just simply convert the result to a list and bind it to your grid.
var query = from item in myDatabaseDataSet.Items
where item.p_Id == p_Id
join diamond in myDatabaseDataSet.Diamond
on item.p_Id equals diamond.p_Id
join category in myDatabaseDataSet.DiamondCategory
on diamond.dc_Id equals category.dc_Id
select new
{
Product = item.p_Name,
Weight = diamond.d_Weight,
Category = category.dc_Name
}.ToList();
dataGridView1.DataSource = query;

Resources