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();
}
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 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..
}
I have two data tables named as dt1Cloned and dt2Cloned. I have implemented linq query for joining these two tables like :
var res = (from p in dt1Cloned.AsEnumerable()
join t in dt2Cloned.AsEnumerable()
on p.Field<Int64>("WorkId") equals t.Field<Int64>("WorkId")
select new
{
DivisionId = p.Field<Int64>("DivisionId"),
DistrictId = p.Field<Int64>("DistrictId"),
MCId = p.Field<Int64>("MCId"),
ACId = p.Field<Int64>("ACId"),
PCId = p.Field<Int64>("PCId"),
DivisionName = p.Field<string>("DivisionName"),
DistrictName = p.Field<string>("DistrictName"),
MCName = p.Field<string>("MCName"),
AssemblyCName = p.Field<string>("AssemblyCName"),
ParliamentaryCName = p.Field<string>("ParliamentaryCName"),
WorkId = p.Field<Int64>("WorkId"),
WorkDetail = p.Field<string>("WorkDetail"),
WorkName = p.Field<string>("WorkName"),
RoadCode = p.Field<string>("RoadCode"),
AdApp = p.Field<string>("AdApp"),
//!Convert.IsDBNull(dr.t1.Field<DateTime?>("Step Start Time")) ? dr.t1.Field<DateTime?>("Step Start Time") : DBNull.Value
//AdminAppDate = !Convert.IsDBNull(p.Field<DateTime>("AdminAppDate")) ? p.Field<DateTime>("AdminAppDate") : DBNull.Value,
AdminAppDate = p.Field<DateTime>("AdminAppDate"),
TargetDate = p.Field<DateTime>("TargetDate"),
AppAmt = p.Field<Int64>("AppAmt"),
TApp = p.Field<string>("TApp"),
TechAppDate = p.Field<DateTime>("TechAppDate"),
TAppAmt = p.Field<Int64>("TAppAmt"),
SourceOfFunds = p.Field<string>("SourceOfFunds"),
AllocatedAmt = p.Field<Int64>("AllocatedAmt"),
ReleaseAmt = p.Field<Int64>("ReleaseAmt"),
WStatus = p.Field<string>("WStatus "),
Expenditure = p.Field<string>("Expenditure"),
ExpenditurePer = p.Field<Int64>("ExpenditurePer"),
ProgressPercentage = p.Field<Int64>("ProgressPercentage"),
Progress = p.Field<string>("Progress"),
UserTypeId = p.Field<Int64>("UserTypeId"),
UserWorkType = p.Field<string>("UserWorkType"),
SchemeId = p.Field<Int64>("SchemeId"),
SchemeName = p.Field<string>("SchemeName"),
AgencyId = p.Field<Int64>("AgencyId"),
AgencyName = p.Field<string>("AgencyName"),
TADate = p.Field<DateTime>("TADate"),
AADate = p.Field<DateTime>("AADate"),
StatusDate = p.Field<DateTime>("StatusDate"),
ProgressDate = p.Field<DateTime>("ProgressDate"),
ReleaseDate = p.Field<DateTime>("ReleaseDate"),
AllocationDate = p.Field<DateTime>("AllocationDate"),
ExpDate = p.Field<DateTime>("ExpDate"),
TimeLimit = p.Field<Int64>("TimeLimit"),
TimeSpent = p.Field<Int64>("TimeSpent"),
TimeSpentPer = p.Field<double>("TimeSpentPer"),
TimeDiff = p.Field<double>("TimeDiff"),
EarthWorkP = p.Field<double>("EarthWorkP"),
EarthWorkC = p.Field<double>("EarthWorkC"),
SolingP = p.Field<double>("SolingP"),
SolingC = p.Field<double>("SolingC"),
WearingP = p.Field<double>("WearingP"),
WearingC = p.Field<double>("WearingC"),
RaisingP = p.Field<double>("RaisingP"),
RaisingC = p.Field<double>("RaisingC"),
StrengtheningP = p.Field<double>("StrengtheningP"),
StrengtheningC = p.Field<double>("StrengtheningC"),
PCLaidP = p.Field<double>("PCLaidP"),
PCLaidC = p.Field<double>("PCLaidC"),
ModifyDate = p.Field<DateTime>("ModifyDate"),
VillageName = t.Field<string>("VillageName"),
}).ToList();
On implimenting this above query, I am getting exception "Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type." . How can I resolve this and handle null values for all datatypes?
If your database field can be nullable, then you will also need to make the C# property that you are reading it into nullable.
Declare your property as a Nullable<DateTime>. There is a convenient shorthand for this: DateTime?.
public class Person
{
// DateOfBirth is NOT nullable - everyone has a date of birth...
public DateTime DateOfBirth { get; set; }
// DateOfDeath IS nullable - not everyone is dead yet...
public DateTime? DateOfDeath { get; set; }
}
Then, when you are projecting out your new object, you can use:
DateOfDeath = p.Field<DateTime?>("DateOfDeath"),
I'm running into two issues:
I tried assigning a ROW_NUMBER to my SQL view and do a running sum based on the row number (and therefore get the sums based on each record), but the resulting performance hit was quite noticeable.
I know how to do this in T-SQL for dates:
The RunningTotal column in this SQL statement is exactly what I need (itemized sums).
But it takes very long to execute.
UPDATE 2 Here is how I created my second view.
CREATE VIEW [dbo].[vCI_UNIONALL_ROW] AS
SELECT ROW_NUMBER() OVER(ORDER BY EffChkDt DESC) AS [Row]
,*
FROM vCI_UNIONALL
GO
My model:
public class UnionAllModel
{
public int? InvoiceNumber { get; set; }
[DataType(DataType.Currency)]
public Decimal? Amount { get; set; }
[DataType(DataType.DateTime)]
public DateTime? EffChkDt { get; set; }
[omitted for clarity]
}
Here's my LINQ query so far:
using (var db = new PLOGITENS01Entities())
{
var rvUnionAll = (from u in db.vCI_UNIONALL
orderby u.EffChkDt ascending
select new UnionAllModel()
{
InvoiceNumber = u.InvoiceNumber,
Date = u.Date,
AccountNumber = u.AccountNumber,
ClientName = u.ClientName,
Amount = u.Amount,
InAmount = u.InAmount,
OutAmount = u.OutAmount,
ClientRiskAdjs = u.ClientRiskAdjs,
SpecificAdjs = u.SpecificAdjs,
EffChkDt = u.EffChkDt,
PayStatus = u.PayStatus,
Type = u.Type
})
.ToList();
return View(new GridModel(rvUnionAll));
}
you can try creating the running sum adding the values to a local variable:
int runningSum = 0;
var rvUnionAll = (from u in db.vCI_UNIONALL.AsEnumerable()
orderby u.EffChkDt ascending
select new UnionAllModel()
{
InvoiceNumber = u.InvoiceNumber,
Date = u.Date,
AccountNumber = u.AccountNumber,
ClientName = u.ClientName,
Amount = u.Amount,
InAmount = u.InAmount,
OutAmount = u.OutAmount,
ClientRiskAdjs = u.ClientRiskAdjs,
SpecificAdjs = u.SpecificAdjs,
EffChkDt = u.EffChkDt,
PayStatus = u.PayStatus,
Type = u.Type,
RunningSum = runningSum += u.Amount
})
.ToList();
From the list
class Delivery
{
public string ProductCode
{
get;
set;
}
public DateTime? OrderedDate
{
get;
set;
}
public DateTime? DeliveryDate
{
get;
set;
}
public Delivery(string pcode, DateTime? orddate, DateTime? deldate)
{
ProductCode = pcode;
OrderedDate = orddate;
DeliveryDate = deldate;
}
}
List<Delivery> DeliveryList = new List<Delivery>();
DeliveryList.Add(new Delivery("P001",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P007",new DateTime(2009,05,17),null));
DeliveryList.Add(new Delivery("P031", new DateTime(2008, 03, 15),
new DateTime(2008,04 ,22)));
DeliveryList.Add(new Delivery("P011",new DateTime(2009,01,27),
new DateTime(2009,02,12)));
DeliveryList.Add(new Delivery("P041",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P051", new DateTime(2009, 01, 27),
new DateTime(2009, 02, 12)));
DeliveryList.Add(new Delivery("P501",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P801",new DateTime(2009,01,27),null));
var query = DeliveryList.OrderBy(p => p.DeliveryDate);
For Report purpose ,During LINQ execution,What is the way to replace null values (Based on Delivery Date) with
message "Yet to be delivered" (DateTime is value type).
var result = DeliveryList.Select(x => new
{
ProductCode = x.ProductCode,
OrderedDate = x.OrderedDate,
DeliveryDate = x.DeliveryDate.HasValue
? x.DeliveryDate.Value.ToString() : "Yet to be delivered"
}).OrderBy(p => p.DeliveryDate).ToArray();
I'm not 100% sure what your asking but it sounds like you want to convert DeliverList into a collection of strings indicating when they were delivered. In the case of a null DeliveryDate though you want the string "Yet to be delivered". If so try the following.
var dates = DeliveryList
.Select(x => x.DeliverDate
? x.DeliverDate.Value.ToString
: "Yet to be delivered");
Darin's solution is neat and I'd go with it. As an alternate consideration...
if you want to keep the type as with the solution above an anonymous type is created and the delivery date will probably end up as a string.
List<Delivery> query = (from d in DeliveryList
select new Delivery
(
d.ProductCode,
d.OrderedDate,
d.DeliveryDate ?? DateTime.Now
)).OrderBy(p=>p.DeliveryDate).ToList();
if you had an empty constructor in your Delivery class you could do something like
List<Delivery> query2 = (from d in DeliveryList
select new Delivery
{
DeliveryDate = d.DeliveryDate ?? DateTime.Now,
OrderedDate = d.OrderedDate,
ProductCode = d.ProductCode
}).OrderBy(p=>p.DeliveryDate).ToList();
The one thing you'd have to do then, is have a meaninful replacement for your DeliveryDate if it's null. I don't think DateTime.Now would be useful and now you'd be stuck with a DateTime field. The advantage obviously, is that you're sitting with a List object which is strongly cast. And helps I guess if later on you do put logic into your contructor.