Format DateTime in an EF query - c#

I have a database table that holds information for received files. One of the columns is a DateTime that specifies when the file was received. I need to get a distinct list of months with the year (MM/YYYY) for files received. I need to get it out of this table. There can be thousands of records in this table so the way I have done it, in Oracle, is in my select statement I format the datetime as MM/YYYY and do a sort desc with a distinct clause on it. This give me a list of just the months that a file was received. Very fast and efficient.
Now I need to do this using EFv4....here's the query I used in Oracle. Anyone know how I can translate it using one of EFs ways of querying?
select distinct
to_char( i.date_received, 'MMYYYY')) MonthAndYear
from table1
order by MonthAndYear desc

Well, don't do it like Oracle. Do it like LINQ.
var q = (from i in Context.Table1
select new
{
Month = i.date_received.Month,
Year = i.date_received.Year
}).Distinct();
To get a DateTime out:
var r = q.AsEnumerable().Select(d => new DateTime(d.Year, d.Month, 1));

Related

How to Write this SQL with linq to sql

Let's say I have a list with 2 or more customerIds and a list with two or more order dates. I want an SQL query like this from linq to sql
SELECT *
FROM Orders
WHERE (CustomerId = #CustomerId1
AND (OrderDate = #OrderDate1 OR OrderDate = #OrderDate2))
OR
(CustomerId = #CustomerId2
AND (OrderDate = #OrderDate1 OR OrderDate = #OrderDate2))
The list with CustomerIds and order dates is not fixed, so I need to loop through it when building the query.
I found a solution for this by using PredicateBuilder
from http://www.albahari.com/nutshell/predicatebuilder.aspx

Select number of occurrences of a string in DataTable

I need find out the number of times a persons name string appears in a DataTable.. Im trying to find out who has resolved the most tickets in 24 hours. I've been able to accomplish this using SQL below but I um un familiar with how to do to this using LINQ. The three columns from the SELECT statement are all varchar(MAX types)
SQL CODE
SELECT Assigned_Individual,Data_Output_Type,assigned_group, count(Assigned_Individual)
FROM [DATABASE].[DBO].[TABLENAME]
GROUP BY Assigned_Individual, Data_Output_Type, assigned_group
ORDER BY count(1) desc
This will produce a result that will have an additional column telling me how many times the persons name "Assigned_Individual" has occurred in this table
It's a bit tricky in LINQ, but you can do it using the below code. I hope you like the sql style syntax:
var query = from table in tablename
group by new { table.Assigned_Individual, table.Data_Output_Type, table.assigned_group }
into grp
select new
{
grp.Key.AssignedIndividual,
grp.Key.Data_Output_Type,
grp.Key.assigned_group,
Count = grp.Count()
};

linq - dynamic group by different functions of date

below my simple sql query
SELECT source, date ,COUNT (*)
FROM query
WHERE source in ('a value')
GROUP BY source, date
it took me a while to understand and implement it in linq notation (also thanks to hints from this site) by finally I did it
var selekt = dt.AsEnumerable();
var alldata = from ad in selekt
where ad["source"].ToString().Equals(this.comboBox1.Text)
group ad by new
{
err = ad["err"],
date = ad["date"]
}into g
orderby g.Key.err ascending, g.Key.channel descending
select new
{
Name = g.Key.err,
Date = g.Key.date,
C = g.Count()
};
It is more or less what I need, it also contains "dynamic" element in where clause.
The last point I can't get it is dynamic group clause.
Depends on values on the form I want to group this query by one of three functions of date: day/week/month. I suppose the most difficult part could be group by week.
Anyway, every hint regarding this topis are welcome

Get Xml field from database, then get value from a particular element

I would like to store a particular element's values from xml documents that I retrieve from the database (if and only if the xml document has it) into a list of ints.
I have started my attempt to do so like this (messages.MessageXML is an Xml type in an SQL Server database):
List<int> messageXml = (from messages in dbContext.Messages
join transactions in dbContext.Transactions
on messages.TransactionID equals transactions.TransactionID
where transactions.CreatedOn >= StartDate
&& transactions.CreatedOn <= EndDate
select messages.MessageXML
).ToList();
Is what I am wanting to do possible in one LINQ query, or do I need to place messages.MessageXML into a List of XmlDocuments / Strings and then try to query for it that way? I can do that, but I would prefer just to have it all done in one query.
I tried to do this based off of some other questions that I have seen:
select messages.MessageXML.Element("IDThatIWant")
But I keep getting an error that states that 'string' does not contain a definition for Element. If it is a namespace that I'm missing, I'm not sure which one it is.
Any help is appreciated!
You might create and dereference the XML-Linq on the fly in the select clause, like this:
select XElement.Parse(messages.MessageXML).Element("IDThatIWant")
However, to separate SQL and XML and including the restriction (only if element has attribute) it would be something like:
var messageXml = from messages in dbContext.Messages
join transactions in dbContext.Transactions
on messages.TransactionID equals transactions.TransactionID
where transactions.CreatedOn >= StartDate
&& transactions.CreatedOn <= EndDate
select messages.MessageXML;
var messages = from m in messageXml select XElement.Parse(m);
var ids = (from msg in messages
let id = msg.Attribute("IDThatIWant")
where !String.IsNullOrEmpty(id)
select Convert.ToInt32(id)).ToList<int>();

LINQ querying for multiple dates and counting rows

Hi I want to know how to do two things with LINQ
This question is probably more a SQL/C# thing I firstly want to query with multiple dates
How would I do this?
For example I want to query every date in 2011 in a DateTime SQL Column So I want to find 01/01/2011 to 31/12/2011 I guess I would replace the first day month numbers with something e.g ##/##/2011
Secondly how do I count rows would it be like this "var rowCount = qRows.Count();"
Thanks
try this :
List<Order> ord = (from o in dc.Orders
where o.OrderDate.Value.Year == 2011
select o).ToList();
int Count = ord.Count;
from x in somethingwithdate
where x.adate > '1/1/2000'
where x.adate < '1/1/2010'
select x
you can also do x.Count
You can do myDate.AddDays(1) repeated as many times as necessary.
Yes, you can do a Count() on the returned LINQ dataset.
Slightly different take on earlier answer(if you were pulling the date from another object for instance):
DateTime myDate = new DateTime(2011,1,1);
var results = (from t in dc.events
where t.event_date.Value.Year.Equals(myDate.Year)
select t).ToList();
int testCount = results.Count();

Categories