Query Dynamic Linq - c#

I need to create a dynamic query where the variable DayOfWeek.Monday is dynamic, how can I set?
DataClassesPDataContext pe = new DataClassesPDataContext();
var qry = from p in pe.R
join q in pe.V on p.V equals q.V_
where p.Data < data
where q.I == `v`
where p.Data.DayOfWeek == `DayOfWeek.Monday`
select(p.Q);
return qry.ToList().Average();

You can extract DayOfWeek into a variable
var day = DayOfWeek.Monday;
var qry = ...
where p.Data.DayOfWeek = day
But be aware. DayOfWeek cannot be used if you execute the query against Entity Framework

Related

Ordering issue with Groupby in Linq

I am facing issues in using order by with group by in linq queries. when I apply group by after order by the ordering is being lost using the following code.
I want to sort all the conversations where type is in ascending. I doubt using Select(x=>x.FirstOrDefault()) is creating some issue.
I am using LINQ queries like this
DateTime? convStartDate = DateTime.Now.AddDays(-90);
DateTime? convEndDate = DateTime.Now;
var limit = 1000;
var offset = 0;
var query = (from conversation in db.textMessagesconversation
join msgParticipants in db.participants on conversation.Id equals msgParticipants.ConversationId
join msg in db.MsgMessages on conversation.Id equals msg.ConversationId
where msgParticipants.UserId == userID && ( (String.IsNullOrEmpty(convStartDate.ToString()) || msg.DateCreatedTime >= convStartDate)
&& (String.IsNullOrEmpty(convEndDate.ToString()) || msg.DateCreatedTime <= convEndDate)
select new RawConversation
{
LastMessageContent = msg.Content,
LastMessageDateTime = msg.DateCreatedTime,
IsAttachment = msg.IsAttachment,
SenderId = msg.SenderId,
MessageId = msg.Id,
Type = conversation.Type,
Name = conversation.Name,
Id = conversation.Id
});
query = query.OrderBy(x => x.Type);
var textmessagesList= query.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).Skip(offset).Take(limit).ToList();

Linq query DateTime.Date.DayOfWeek

Trying to get only Thursdays of 1 year back
using (var context = new Context1())
{
// Get 1 year back only Thursday
var oneYearEarlier = DateTime.Now.AddYears(-1);
var query = (from c in context.Daily25Data
where c.Date > oneYearEarlier && c.Date.DayOfWeek == DayOfWeek.Thursday
select c).ToList();
Console.WriteLine(query);
}
and getting
Additional information: The specified type member 'DayOfWeek' is not
supported in LINQ to Entities. Only initializers, entity members, and
entity navigation properties are supported.
This is a clever solution using EntityFunctions.DiffDays
from his post:
DateTime firstSunday = new DateTime(1753, 1, 7);
var bookings = from b in this.db.Bookings
where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1
select b;
LINQ will not recognize the second part of your query into SQL. You need to break your query up in order to perform the filter.
using (var context = new algoventurelab_db1Context())
{
// Go one year back from current date
var startDate = DateTime.Today.AddYears(-1);
// This will get all dates in context greater than start date.
var query1 = (from c in context.Daily25Data
where c.Date >= startDate
select c).AsEnumerable();
//this will filter only thurdays
var query = from c in query1
where c.Date.DayOfWeek == DayOfWeek.Thursday
select c).ToList();
Console.WriteLine(query);
}

Linq date comparision

My query is like
var TMJM = (from TT in r2ge.Transcription_Tracker
join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
select new
{
Trans_Id = TMA.Transcription_Id,
Modified_dtm = TMA.Modified_dtm
}).Distinct();
var qq = TMJM.Where(dr => (dr.Modified_dtm.Date >= sev_back_datetime) && (dr.Modified_dtm.Date <= DateTime.Now.Date));
It gives output Enumeration yielded no results while Data is there
But when I separate start date and end date then It will show date but when I combine both start and end date then It won't give output..
Any mistake in query?
Evaluating each part of the date could be fraught with issue. I am assuming you are doing this to remove the time portion which can sometimes be problematic. Subsequently you can just evaluate the 'date' portion of the date time variable. This little example should explain.
class Program
{
static void Main(string[] args)
{
List<DateTime> dates = new List<DateTime>();
dates.Add(DateTime.Now.AddDays(-50));
dates.Add(DateTime.Now.AddDays(-51));
dates.Add(DateTime.Now.AddDays(-52));
dates.Add(DateTime.Now.AddDays(-53));
dates.Add(DateTime.Now.AddDays(-99));
dates.Add(DateTime.Now.AddDays(-100));
dates.Add(DateTime.Now.AddDays(-101));
var sev_back_datetime = DateTime.Now.AddDays(-100);
Console.WriteLine(sev_back_datetime.Date.ToShortDateString());
Console.WriteLine("---------------------");
var query = from date in dates
where date.Date >= sev_back_datetime.Date &&
date.Date <= DateTime.Now.Date
select date;
foreach (var date in query.ToList())
Console.WriteLine(date.ToShortDateString());
Console.ReadLine();
}
}
EDIT - a direct example for you.
var TMJM = (from TT in r2ge.Transcription_Tracker
join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
select new
{
Trans_Id = TMA.Transcription_Id,
Modified_dtm = TMA.Modified_dtm
}).Distinct();
var qq = TMJM.Where(dr => (EntityFunctions.TruncateTime(dr.Modified_dtm) >= EntityFunctions.TruncateTime(sev_back_datetime)) && (EntityFunctions.TruncateTime(dr.Modified_dtm) <= EntityFunctions.TruncateTime(DateTime.Now)));

SQL to LINQ C# EntityFramework

I'm on my way to convert all my straight SQL programms to Entity Framework.
So I need LINQ and LE.
But I'm not able to do this in LINQ:
SELECT
a.abteilung,
sum(d.kosten)
FROM
tdaten d,
abteilung a
WHERE
d.sourcenr = a.sourcenr AND
d.datum between '" + string.Format("{0:yyyy-MM-dd}", DTP_from.Value) + "'
and '"+string.Format(format: "{0:yyyy-MM-dd}", arg0: DTP_to.Value)+"'
GROUP BY
a.abteilung;", _con);
Thanks
Something like this?
from a in abteilung
join d in tdaten
on a.sourcenr equals d.sourcenr
where d.datum >= DTP_from.Value && d.datum <= DTP_to.Value
group d by a.abteilung into g
select new
{
abteilung = g.Key,
kosten = g.Sum(d => d.kosten)
}
An option.
The whole can b breakdown into 3 sub-queries in LINQ.
Get the Records
Take the sum
The group by the result.
Following are the queries.:
var results = from a in abteilung
join d in tdated on d.sourcenr equals a.sourcenr
where
d.dateum >= fromDate && d.datum <= ToDate.AddDays(1)
select new {a.abteilung, d.kosten};
var sumOfKotsen = results.Sum(x=>x.kosten);
var groupResult = results.GroupBy(x=>x.abteilung);
Assuming that the dateFrom and ToDate are the DateTime objects.

EF - linq2entities does not recognize .tostring() method?

I'm unable to compile the below code and I'm getting the following error:
LINQ to Entities does not recognize the method 'System.String ToString()
I'm a bit surprised because I was able to do this in Linq2SQL but can't do it in Entity Framework.
Could I please get any help rewriting the below code ? I've seen a few examples related to this error but I couldn't find something that is specific to this scenario. Thanks
using (ctx)
{
var productResults = (from q in ctx.Products
where q.ProductId == productId && q.Model == productModel
select new Models.ProductDTO
{
Id = q.ProductId,
Name = q.Name.ToString(),
Year = q.Year.ToString("MMM ddd d HH:mm yyyy"),
Model = q.Model,
Description = q.Description.ToString()
}).Distinct().ToList().AsParallel();
Department.Products = productResults;
}
First get list from context
var productResults = ctx.Products.where(q => q.ProductId == productId && q.Model == productModel).ToList();
Then query is and select new Type as ProductDTO
var productDTO = (from q in productResults
select new Models.ProductDTO
{
Id = q.ProductId,
Name = q.Name.ToString(),
Year = q.Year.ToString("MMM ddd d HH:mm yyyy"),
Model = q.Model,
Description = q.Description.ToString()
}).Distinct().ToList().AsParallel();
AFTER COMMENT
IEnumerable:
IEnumerable<Products> list = context.Products.Take(10);
// after this line data load the memory that fetched from DB.
SQL Output:
Select * FROM Table
IQuerable:
IQuerable<Products> list = context.Products.Take(10);
// data still not fetch from DB
SQL Output:
Select Top 10 FROM Table
you may also do this in one query;
var productResults = ctx.Products.Where(q => q.ProductId == productId && q.Model == productModel).ToList()
.Select<Product, ProductDTO>(m =>
{
Models.ProductDTO dto= new Models.ProductDTO();
dto.Id = m.ProductId;
dto.Name = m.Name.ToString();
dto.Year = m.Year.ToString("MMM ddd d HH:mm yyyy");
dto.Model = m.Model;
dto.Description = m.Description.ToString();
return dto;
}).Distinct().ToList().AsParallel();
there may be a better way, but breaking it into two queries may work.
var productResults = (from q in ctx.Products
where q.ProductId == productId && q.Model == productModel
select q).ToList();
var temp = from o in productResults
select new Models.ProductDTO
{
Id = q.ProductId,
Name = q.Name.ToString(),
Year = q.Year.ToString("MMM ddd d HH:mm yyyy"),
Model = q.Model,
Description = q.Description.ToString()
}).Distinct().ToList();

Categories