How do I display only datepart of datetime field in LINQ query? - linq

I have a datetime field in a database which when retrieved should only display the date without the time. Can you please let me know how to do it? Here is the query I wrote:
var queryProductEventCustomers = (from r in DbContext.ProductEventCustomers
from s in DbContext.CustomerProducts
where r.Customers_Id == customerID && r.Customers_Id
== s.Customers_Id && s.Products_Id == productID
select new
{
r.Id,
r.Customers_Id,
r.StartTime
The starttime is a datetime field. So, can you please let me know how to do it?

Use the Short Date format:
r.StartTime.ToString("d", DateTimeFormatInfo.InvariantInfo)
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
The link shows you how to work with all standard date and time formats.

Use the ToShortDateString() method on DateTime.
select new
{
Id = r.Id,
Customers_Id = r.Customers_Id,
Date = r.StartTime.ToShortDateString()
}

Just choose the date portion:
select new
{
Id = r.Id,
Cust_id = r.Customers_Id,
Date = r.StartTime.Date
}

Try this
select new
{
ID = r.Id,
CustomerID = r.Customers_Id,
StartDate = r.StartTime.ToString("dd/MM/yyyy")
}

Related

linq query issues with date type data

I want to retrieve the data based on sku number like in below code,in this process i got all data same as it is in database but "date type" value is display like "01/01/0001".But i need to "date type" data like as it is in database date.any modifications i need to do .please help me out.
public IEnumerable<SKUDvo> getdatabysku()
{
eshop_dbContext dbcontext123 = new eshop_dbContext();
var productinfoQuery321 = (from productInfo321 in dbcontext123.ProductMasters
where productInfo321.SKU == "s121"
select productInfo321);
IList<SKUDvo> productList123 = new List<SKUDvo>();
foreach (var proitems in productinfoQuery321)
{
productList123.Add(new SKUDvo
{
skuno = name,
ProductId = proitems.ProductId,
CategoryID = proitems.CategoryID,
ManufaturerId = proitems.ManufaturerId,
ItemNo = proitems.ItemNo,
ProductName = proitems.ProductName,
DeletedInd = proitems.DeletedInd,
});
}
return productList123;
}
My table is like below.
empid ename dateofjoin
10 sarath 26/02/2003
20 jai 16/03/2001
my result is like below
10 sarath 01/01/0001
20 jai 01/01/0001
It looks like you have an DateTime that hasn't been set. The default value of a DateTime is "01/01/0001 00:00:00".
// outputs the value of an empty DateTime: "01/01/0001 00:00:00"
Console.WriteLine(default(DateTime));
Are you sure that the dateofjoin is assigned? I don't see it in you code.

How to solve this in LINQ query?

I was working on MVC3 project. I need help writting Linq expression. My model is something like this.
Model Class
public int Id { get; set; }
public int DetCount { get; set; }
I need to do something like this,
DetCount = (from sel in db.PoDetails where sel.PoId == Id select sel).Count(); // Id is current model Id.
Based on the parent table Id, i need to get the child table records count.
Example
Parent Table
Id Name
1 XYZ
2 ABC
Child Table
Id P_Id
1 1
2 1
3 2
DetCount = (from sel in db.child where sel.P_Id == Id select sel).Count(); // if Id= 1
Result
DetCount = 2;
I have written the code something like this.
Code
model = ...
select new porders
{
Id = p.Id, //This Id is passed to next statement for DetCount.
DetCount = (from sel in db.PoDetails where sel.PoId == Id select sel).Count(); // I need to pass value from another linq query.
}
Please help me for this.
Thanks,
var result = select new porders
{
Id = p.Id,
PODate = p.Date.Value,
RefNo = p.RefNo,
Status = resloc.Description,
Supplier = resstat.Name,
DetCount = db.PoDetails
.Select(p => p.sel)
.Where(sel.PoId == asd.Id).Count()
}
Is it just the count you want? If so this should work:
var DetCount = db.PoDetails.Where(sel=>sel.PoId == Id).Count(); // Id is current model Id.
Cheers :)

Error: "The xml data type cannot be selected as DISTINCT because it is not comparable."

In my code I have the following Linq Query:
IQueryable<Data> charts = (from report in ctx.Charts group report by new
{
Name = report.ChartTitle.ChartType.ChartCategory.CategoryName,
id = report.ChartTitle.ChartType.ChartCategory.ChartCategoryId,
Period = report.Period
} into d
select new Data
{
Name = d.Key.Name,
Id = d.Key.id,
Period = d.Key.Period,
Reports = from r in d group r by new
{ Title = r.ChartTitle.Name, id = r.ChartTitle.ChartTitleId } into rs
select new Report
{
Title = rs.Key.Title,
Id = rs.Key.id,
Charts = (from c in rs group c by new
{
ChartId = c.ChartId,
FiscalYear = c.FiscalYear,
ModifiedDate = c.ChartView.ModifiedDate,
Function = c.Function.DisplayName,
ChartData=c.ChartView.ViewData
} into cs
select new ChartInfo
{
ChartId = cs.Key.ChartId,
FiscalYear = cs.Key.FiscalYear,
ModifiedDate = cs.Key.ModifiedDate,
Function = cs.Key.Function,
ChartData=cs.Key.ChartData
})
}});
In the above code if I exclude the "ChartData" field (which is of XML datatype), the query executes fine. But when ever I include this field it throws the following error :"The xml data type cannot be selected as DISTINCT because it is not comparable."
Let me know what I am missing here?
You can't group by XML types. This is a SQL restriction, not a LINQ-to-SQL retriction. (See Group by on XML column field with LINQ and select an xml type column in select query with group by SQL Server 2008)
Do you need to group by the XML column? The alternative would be to group by your other columns and then select the first XML value as a result.
Charts = (from c in rs group c by new
{
ChartId = c.ChartId,
FiscalYear = c.FiscalYear,
ModifiedDate = c.ChartView.ModifiedDate,
Function = c.Function.DisplayName,
} into cs
select new ChartInfo
{
ChartId = cs.Key.ChartId,
FiscalYear = cs.Key.FiscalYear,
ModifiedDate = cs.Key.ModifiedDate,
Function = cs.Key.Function,
ChartData=cs.Value.FirstOrDefault().ChartData
})
When using LINQ-to-SQL the items being grouped are still accessible - you don't need to include every 'selected' property / column in the group by` clause like you would in SQL.
You did not tell us what is the actual datatype of the ChartData, but from the error you are describing it looks like the problem is that whatever this datatype is it does not implement the IComparable interface which is a required interface if you want instances of the datatype to be comparable

C# linq dates between

I am tring to get a list of dates from my db that will eventually be used to populate a calendar. Each 'calendar event' has a start date & end date, i need to get all dates between & including the start & end date.
i am stuck on the WHERE statement, as i am not sure what to use for this
public List<EventFeed> GetCalendarDates()
{
return (from eventsList in GetEventsList()
select new EventFeed()
{
//EventDate = todo
}).ToList();
}
UPDATE
just to be clear, if i have a calendar event called foobar which starts on 22/08/2010 and ends on 24/08/2010, then i want my list return:
22/08/2010,
23/08/2010,
24/08/2010
thanks
kb
I had to do something similar recently, I used a Func<> to extract the dates from the range and used the result in the linq query.
I have added the same Func to your Linq query below. You didn't specify the name of the object that is returned by GetEventsList() so just replace the EventItem type for the first type parameter in the Func<> with whatever type you need.
public static List<EventFeed> GetCalendarDates()
{
Func<EventItem, List<DateTime>> extractEventDates = eventItem =>
{
var dates = new List<DateTime>();
for (var date = eventItem.StartDate;
date <= eventItem.EndDate;
date = date.AddDays(1))
{
dates.Add(date);
}
return dates;
};
return (from eventItem in GetEventsList()
from eventDate in extractEventDates(eventItem)
select new EventFeed
{
EventDate = eventDate
}).ToList();
}
You mean you want to select all the events that started on or after start date and ended on or before end date!
If yes, then this will help
var query = from #event in events
where #event.Start.Date >= startDate.Date
&& #event.End.Date <= endDate.Date
select #event;

Dealing with a null datetime element within xml using linq

HI
I have an example document that looks like
<ItemEntry>
<PurchaseDate>2010-03-18T20:36:32.81108+13:00</PurchaseDate>
<StoreGUID>0a0324ad-5f99-486a-a2d0-870bc6991e9f</StoreGUID>
<ExpiryDate />
<CardID>111111</CardID>
<PurchaseAmount>0</PurchaseAmount>
<RedeemedAmount />
<EntryType>1</EntryType>
<RedeemedDate />
<SalesAssistantID>0</SalesAssistantID>
</ItemEntry>
As you can see there are couple of elements ExpiryDate and RedeemedDate are are empty.
var q = from c in xml.Elements("ItemEntry")
select new mdDetail {
PurchaseDate = (DateTime)c.Element("PurchaseDate"),
StoreGUID = (Guid)c.Element("StoreGUID"),
ExpiryDate = (DateTime?)c.Element("ExpiryDate")??DateTime.MinValue,
CardID = (int)c.Element("CardID"),
PurchaseAmount = (double)c.Element("PurchaseAmount"),
RedeemedAmount = (double?)c.Element("RedeemedAmount"),
EntryType = (int)c.Element("EntryType"),
RedeemedDate = (DateTime?)c.Element("RedeemedDate") ??DateTime.MinValue,
SalesAssistantID = (int)c.Element("SalesAssistantID"),
}
;
foreach (var item in q)
{
}
I am not sure how to deal with the null element value,
I have tried ??DateTime.MinValue and ??null however both give me a "
String was not recognized as a valid DateTime." error.
Any suggestions?
Thank you
ExpiryDate = String.IsNullOrEmpty((string)c.Element("ExpiryDate"))?
DateTime.MinValue : DateTime.Parse((string)c.Element("ExpiryDate"))
"You could also use null instead of DateTime.MinValue if ExpireyDate is
declared to be nullable"
#Gabe, you can't just use null - you need to use (DateTime?)null because the compiler won't know how to convert null into a DateTime object
So if you want the value to just be a blank (null) this would be the final code:
ExpiryDate = String.IsNullOrEmpty(c.Element("ExpiryDate").Value)?
(DateTime?)null : DateTime.Parse(c.Element("ExpiryDate").Value)
Assuming DateTime is a declared a nullable (DateTime?)

Resources