I'm writing linq query as below: -
from eventDetails in CurrentDataContext.EventCarriers
join eventlog in CurrentDataContext.EventLogCarriers on eventDetails.EventID equals eventlog.EventId into hhh
from eventlog in hhh.DefaultIfEmpty()
join quiz in CurrentDataContext.QuizCarriers on eventDetails.EventID equals competition.EventId into aaa
from quiz in aaa.DefaultIfEmpty()
where eventDetails.EventID == eventId && eventDetails.EventStatusId == 1 && eventlog.CreatedBy == userId
group new { eventDetails, quiz, eventlog } by new
{
eventDetails.EventID,
eventDetails.Name
} into g
select new VenueModel
{
Name = g.Key.Name,
EventId = g.Key.EventID,
StartDate = g.Key.StartDate,
EndDate = g.Key.EndDate,
EventDescr = g.Key.EventDescr,
EventIconPath = g.Key.EventIconPath,
EventImagePath = g.Key.EventImagePath,
Prizes = (from a in g.Select(a => a.competitions)
group a by new
{
a.PrizeId,
a.PrizeIconPath,
a.CompetitionDescr,
a.PrizeImagePath,
a.EndDate,
a.StartDate,
a.Name,
a.EventId,
a.StatusId
} into x
select new CCompetitionModel
{
PrizeDescrption = x.Key.PrizeDescr,
PrizeIconPath = x.Key.PrizeIconPath,
PrizeId = x.Key.PrizeId,
}).ToList(),
}).FirstOrDefault();
But I'm getting an error like 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.
//Declare your class property nullable.
//For example, if you are getting start date null from database, then your property will be like following.
public class Event
{
public DateTime? StartDate{get; set;}
//add other properties of this class here..
}
Related
I am trying to add a List inside a new List using C# and I get the following error:
System.NotSupportedException: 'A type that implements IEnumerable 'System.Collections.Generic.List`1
I tried a few methods to implement it but it didn't go trough.
This is what I have done:
public List<ExtendEmp> GetEmpDatas()
{
var result2 = from emp in db.employees
join dep in db.departments on emp.departmentID equals dep.ID
orderby emp.ID
select new ExtendEmp
{
ID = emp.ID,
fname = emp.fname,
lname = emp.lname,
startWorkYear = emp.startWorkYear,
name = dep.name,
manager = dep.manager,
ExtendShiftz = new List<ExtendShft>()
};
return result2.ToList();
}
The specific list I'm trying to add is ExtendShiftz which is initialised here:
public List<ExtendShft> GetShftDatas()
{
var result3 = from emp in db.employees
join emps in db.employee_shift on emp.ID equals emps.employeeid
join shft in db.shifts on emps.shiftid equals shft.ID
select new ExtendShft
{
ID = shft.ID,
employeeid = emps.employeeid,
fname = emp.fname,
lname = emp.lname,
shiftid = emps.shiftid,
date = shft.date,
startTime = shft.startTime,
endTime = shft.endTime
};
return result3.ToList();
}
and of course i added it inside my model that way:
public ExtendEmp()
{
ExtendShiftz = new List<ExtendShft>();
}
public List<ExtendShft> ExtendShiftz { get; set; }
If you guys have any idea what i am doing wrong there i'd be happy to read.
I'm trying to get some data to format in the ShortDateTime format of "MM/dd/yyyy" but everything I'm trying is not working.
I have the following EF below and the field I'm specifically looking at is the ExpireDate. When I try to use a DateTime.Parse around the field I get an error cannot convert from 'System.DateTime?" to 'string'. Without the DateTime.Parse then the date displays as 3/15/2017 12:00:00 AM.
I tried using Data Annotations on the Model as well but that doesn't seem to work either.
Any suggestions?
EF query
data = (from e in ctx.clock_emp_excep_hist
join g in ctx.clock_group on e.group_id equals g.group_id
join emp in ctx.employee on e.emp_id equals emp.emp_id
where e.group_id == 4
select new
{
UpdateDate = e.create_date,
UpdateType = e.add_delete_ind,
GroupId = e.group_id,
GroupName = g.group_name,
Reason = e.reason,
ExpireDate = e.expiration_date,
UpdateEmployeeId = e.emp_id,
UpdateFirstName = emp.emp_firstname,
UpdateLastName = emp.emp_lastname
}).Select(e => new EmployeeExceptionLog {
UpdateDate = e.UpdateDate,
UpdateType = e.UpdateType == "A" ? "Add" : "Delete",
GroupId = e.GroupId,
GroupName = e.GroupName,
Reason = e.Reason,
ExpireDate = DateTime.Parse(e.ExpireDate),
UpdateEmployeeId = e.UpdateEmployeeId,
UpdateFirstName = e.UpdateFirstName,
UpdateLastName = e.UpdateLastName
}).ToList();
}
Property in class
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode=true)]
public DateTime? ExpireDate { get; set; }
More info:
This is how I'm displaying the data in the View.
#foreach (var item in Model.AuditLogs)
{
<tr class="#(item.UpdateType == "Delete" ? "danger" : "")">
<td>#item.UpdateDate</td>
<td>#item.UpdateType</td>
<td>#item.Reason</td>
<td>#item.ExpireDate</td>
<td>#item.UpdateEmployeeId - #item.UpdateFirstName #item.UpdateLastName</td>
</tr>
}
The DataType in the Oracle Database is DateTime?.
public DateTime? ExpireDate { get; set; }
Its nullable date so you can have Null value for ExpireDate.
"cannot convert from 'System.DateTime?" to 'string'"
ExpireDate = DateTime.Parse(e.ExpireDate),
DateTime.Parse takes string as a parameter.
i would change this to
ExpireDate = ((e.ExpireDate != null) ? (DateTime)e.ExpireDate : "SOME DEFAULT DATE"),
Also in View you can display using ToShortDateString() if your model property is dateTime.
<td>#item.ExpireDate.ToShortDateString()</td>
here is more info about DateTime.
You can't parse nullable DateTime.
To convert nullable DateTime into a formatted string :
ExpireDate != null ? ExpireDate.Value.ToString("MM/dd/yyyy") : "ERROR";
Update your query into this:
data = (from e in ctx.clock_emp_excep_hist
join g in ctx.clock_group on e.group_id equals g.group_id
join emp in ctx.employee on e.emp_id equals emp.emp_id
where e.group_id == 4
select new
{
UpdateDate = e.create_date,
UpdateType = e.add_delete_ind,
GroupId = e.group_id,
GroupName = g.group_name,
Reason = e.reason,
ExpireDate = e.expiration_date,
UpdateEmployeeId = e.emp_id,
UpdateFirstName = emp.emp_firstname,
UpdateLastName = emp.emp_lastname
}).Select(e => new EmployeeExceptionLog {
UpdateDate = e.UpdateDate,
UpdateType = e.UpdateType == "A" ? "Add" : "Delete",
GroupId = e.GroupId,
GroupName = e.GroupName,
Reason = e.Reason,
ExpireDate = ExpireDate != null ? ExpireDate.Value.ToString("MM/dd/yyyy") : "ERROR",
UpdateEmployeeId = e.UpdateEmployeeId,
UpdateFirstName = e.UpdateFirstName,
UpdateLastName = e.UpdateLastName
}).ToList();
}
What does this error mean?
My error is:
Cannot implicitly convert type 'System.Linq.IQueryable<System.Linq.IGrouping<decimal,Project1.Domain.Models.DepartmentBreakdownReport>>' to 'System.Linq.IQueryable<Project1.Domain.Models.DepartmentBreakdownReport>'. An explicit conversion exists (are you missing a cast?)
I would like to know what it is in order for me to be able to fix it. It only happens when I add a LINQ GroupBy onto my results.
public IQueryable<DepartmentBreakdownReport> GetDepartmentBreakdownBySupplierIDAndReviewID(int ClientID, int? SupplierID, int? ReviewID) {
return (from d in Db.Details
join h in Db.Headers
on new { d.ClientID, d.ClaimID }
equals new { h.ClientID, h.ClaimID }
where d.ClientID == ClientID && h.SupplierID == SupplierID
join sd in Db.SuppDepts
on new { a = d.ClientID, b = d.CategoryID ?? 0 }
equals new { a = sd.ClientID, b = sd.CategoryID }
join r in Db.Reviews
on new { h.ClientID, h.ReviewID }
equals new { r.ClientID, r.ReviewID }
join rp in Db.ReviewPeriods
on new { a = r.ClientID, b = r.ReviewPeriodID ?? 0 }
equals new { a = rp.ClientID, b = rp.ReviewPeriodID }
where r.ReviewID == ReviewID
join su in Db.Suppliers
on new { h.ClientID, h.SupplierID }
equals new { su.ClientID, su.SupplierID }
select new DepartmentBreakdownReport {
DepartmentName = sd.DepartmentName,
SumOfAmount = d.Amount,
SupplierID = h.SupplierID,
ReviewID = h.ReviewID,
ReviewName = rp.ReviewPeriodName,
SupplierName = su.SupplierName,
ClientID = d.ClientID
}).GroupBy(r=>r.Amount);
}
What does this error mean?
Your return type is IQueryable<DepartmentBreakdownReport> yet you are attempting to return a IGrouping<decimal,Project1.Domain.Models.DepartmentBreakdownReport>
When you call .GroupBy you change the return type to IGrouping rather than IQueryable, it also introduces the decimal as part of the IGrouping expression (Which is the amount variable you are grouping by).
To fix it you can simply change the method signature to:
public IGrouping<decimal,Project1.Domain.Models.DepartmentBreakdownReport> GetDepartmentBreakdownBySupplierIDAndReviewID(int ClientID, int? SupplierID, int? ReviewID)
To me, the method name GetDepartmentBreakdownBySupplierIDAndReviewID would imply:
Firstly that the method return type would be something like this, assuming types of int for SupplierId and ReviewId :
IGrouping<Tuple<int, int>, IQueryable<DepartmentBreakdownReport>>
GetDepartmentBreakdownBySupplierIDAndReviewID(...)
Secondly that the return should be on a final projection something like:
select new DepartmentBreakdownReport { ... })
.GroupBy(r => new Tuple<int, int>(r.SupplierID, r.ReviewID));
I have the following query in controller and I want to store a column value in a variable but I am not being able to iterate it. Here is my code:
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Status equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where(SRMAs.Id == srmaid)
group SRMADetails by new
{
SRMADetails.Id,
SRMADetails.SRMAId,
SRMADetails.SupplierPartNum,
SRMAs.PONumber,
SRMAs.ActualAmount,
SRMAs.ApprovedOn,
SRMAs.Status,
SRMAs.TrackingNumber,
SRMAs.SupplierRMANumber,
SRMAs.RequestedFromSupp,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate,
PurchaseOrders.suppliersOrderNumber
} into grp
select new
{
grp.Key.Status,
grp.Key.SRMAId,
grp.Key.Id,
grp.Key.PONumber,
grp.Key.SupplierRMANumber,
grp.Key.ActualAmount,
grp.Key.SupplierPartNum,
grp.Key.RequestedFromSupp,
grp.Key.TrackingNumber,
grp.Key.ApprovedOn,
grp.Key.SupplierName,
grp.Key.StatusName,
grp.Key.PODate,
grp.Key.suppliersOrderNumber,
grp.Key.CreatedOn,
Sum = grp.Sum(SRMADetails => SRMADetails.Cost * SRMADetails.QtyReturned)
}
).ToList();
System.Collections.IEnumerable et = (System.Collections.IEnumerable)srmas;
IEnumerator it = et.GetEnumerator();
while (it.MoveNext())
{
SRMA current = (SRMA)it.Current;
Response.Write(current.Status);
}
ViewBag.SRMAs = srmas.Select(srma => new IndexViewModel
{
Id = srma.SRMAId,
SupplierRMANum = srma.SupplierRMANumber,
SRMADetailsID = srma.Id,
PONumber = srma.PONumber,
CreatedOn = srma.CreatedOn,
SupplierName = srma.SupplierName,
SRMAStatus = srma.StatusName,
Status = srma.Status,
suppliersOrderNumber = srma.suppliersOrderNumber,
PODate = srma.PODate,
Sum = srma.Sum,
TrackingNumber = srma.TrackingNumber,
ActualAmount = srma.ActualAmount
}).ToList();
I just want to get Status value of first record. How do I do it?
I am trying to do something like the following:
I am not sure how to initialize teh restultCLList as I cannot set it to null.
var resultCLlist = null;
if (RdoStatus.SelectedValue == "Incomplete")
{
resultCLList = (from ms in db.ver_ServiceReport
join gc in db.map_Sit
on ms.SiteId equals gc.SiteID
where gc.CompanyId == companyId
select new ServiceReport
{
VerificationId = ms.VerificationId,
SiteId = ms.SiteId,
}
).ToList();
}
else
{
resultCLList = (from ms in db.ver_ServiceReport
join gc in db.map_Sites
on ms.SiteId equals gc.SiteID
where gc.CompanyId == companyId
select new ServiceReport
{
VerificationId = ms.VerificationId,
SiteId = ms.SiteId,
SiteName = gc.SiteName,
TimeStamp = ms.TimeStamp,
EntryDate = ms.EntryDate,
Supplier = ms.Supplier
}
).ToList();
}
Why don't you use List<ServiceReport> instead of var ?
You can't initialize var to a null value, because null is not a type itself.You can cast it to object but it won't be safe.var is useful if you don't know the returning type of the expression on the right side, or if the type name is too long.In this case you know the type, so simply don't use var.