Order LINQ by "string" name - linq

PROBLEM SOLVED!!!
The solution is Linq.Dynamic
You do it like this:
(from c in Context.AccountCharts
where c.Account_FK == account && c.Year_FK == year select c).OrderBy(order);
You have to download the System.Linq.Dynamic.dll and include it into your project.
Is there a way to order a linq query by the name of a field. like this:
from c in Context.AccountCharts
where c.Account_FK == account && c.Year_FK == year
orderby c["ColName"] select c;
Or
from c in Context.AccountCharts
where c.Account_FK == account && c.Year_FK == year
orderby c.GetType().GetField("ColName") select c;
None of these two works but I hope you know of a way to do this.

I spend to many time to resolve this issue, but didn't find any better than:
var queryExpression;
if (c["ColName"]=="CreateDate")
queryExpression.OrderBy(x => x.CreateDate);

Hope this will work too though not tested
Context.AccountCharts.Where(c=>c.Account_FK == account && c.Year_FK == year).OrderBy(o=>o.order);

Related

Does the second from clause in this LINQ query do anything?

I am trying to simplify a C# method that includes the following query:
var matchingDeviceKeys =
from dev in data.Elements("Key1")
where dev.Element("Key2").Element("Key3").Element("VendorID").Value == device.Vendor &&
dev.Element("Key2").Element("Key3").Element("ProductType").Value == device.ProductType &&
dev.Element("Key2").Element("Key3").Element("ProductCode").Value == device.ProductCode
from rev in dev.Element("Key2").Element("Key3").Element("Key4").Elements("MajorRev")
where rev.Attribute("Number").Value == device.MajorRevision &&
rev.Attribute("DefaultMinorRev").Value == device.MinorRevision.ToString(CultureInfo.InvariantCulture)
select dev.Element("Key6").Element("Key7").Element("Key8");
The "rev" target for the second from clause is never used in the select line, making me wonder if that entire second from clause is doing anything. If it is doing something, what is it doing?
My apologies for obfuscating the element names. I have to be careful in sharing proprietary code.

Linq code have errors when i use Distinct()

Guys I am working on a code and I need to do a distinct selecting just 2 columns. Can you guys tell me what is wrong with this code ?
foreach (var lbd in (from lbdrow in Db.LaborDtl
where (lbdrow.Company==epged.Company && epged.EmpID==lbdrow.EmployeeNum && lbdrow.PayrollDate==epged.PayrollDate)
select new {Company==lbdrow.Company && ProjectID==lbdrow.ProjectID})).Distinct()
Guys my apologies for the stupid question i found the solution
foreach (var lbd in (from lbdrow in Db.LaborDtl
where (lbdrow.Company==epged.Company && epged.EmpID==lbdrow.EmployeeNum && lbdrow.PayrollDate==epged.PayrollDate)
select new {Company==lbdrow.Company && ProjectID==lbdrow.ProjectID}).Distinct())

How to make efficient search with LINQ in MVC4? [duplicate]

This question already has answers here:
entity framework: conditional filter
(3 answers)
Closed 6 years ago.
Hi I am developing MVC4 application. I am developing one search page which contains 5 textboxes and search button in which only one textbox is mandatory field. Remaining are not mandatory. I want to have AND of all 5 textbox values. My query is as below.
var logDetails = (from c in db.ts_upldlog_content
join tbl in db.ts_upld_doc on c.upld_docid equals tbl.upld_docid
join doc in db.tm_doc_type on tbl.upld_doctypeid equals doc.doc_typeid
where
(tbl.upld_clientid == clientId && tbl.upld_employeeid == employeeID && tbl.upld_empcitizenid == citizenId && tbl.upld_doctypeid == typeofDocument && EntityFunctions.TruncateTime(c.updatedOn) >= start && EntityFunctions.TruncateTime(c.updatedOn) < end)
select new logdetails
{
//Getting all properties
}).toList();
My problem is In the above query start and end are mandatory so i will get some value from UI. Let me explain one scenario. User will supply start and end and remaining will be null. My query will not yield results because I am doing && operation and my other fields may have some value in DB.
Lets conside below table.
clientID EmployeeID EmpCitiID docType Date
123 456 456 1 10/19/2016
When i Pass only Date my query will not work because I am doing && operation. so Is there any way to achieve this scenario? Any help would be appreciated. Thank you.
tbl.upld_clientid == clientId && tbl.upld_employeeid == employeeID && tbl.upld_empcitizenid == citizenId && tbl.upld_doctypeid == typeofDocument &&
(EntityFunctions.TruncateTime(c.updatedOn) >= start && EntityFunctions.TruncateTime(c.updatedOn) < end ) )
missing parenthesis

Use Linq query to compare date only with DateTime field

I need to compare just the date only in a Linq query that involves a datetime field. However, the syntax below results in the following error message
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Does anyone know how to extract just the date out of a datetime field?
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken.Date == course.DateTaken.Date &&
a.SymNumber == symNumber
select a;
It might seem a little roundabout, but you can use the SqlFunctions class' DateDiff method for doing this. Just pass in both values and use "Day" for finding the difference between them in days (which should be 0 if they are on the same day).
Like the following:
from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
SqlFunctions.DateDiff("DAY", a.DateTaken, course.DateTaken) == 0 &&
a.SymNumber == symNumber
select a;
You can use EntityFunctions.TruncateTime() under the namespace System.Data.Objects
Ex.
db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B")
Works like charm.
UPDATE
This function works only when you querying entities through LINQ. Do not use in LINQ-Object.
For EF6 use DbFunctions.TruncateTime() under System.Data.Entity namespace.
You can do it like bellow:
var data1 = context.t_quoted_value.Where(x => x.region_name == "Pakistan"
&& x.price_date.Value.Year == dt.Year
&& x.price_date.Value.Month == dt.Month
&& x.price_date.Value.Day == dt.Day).ToList();
you must use System.Data.Entity.DbFunctions.TruncateTime
try this
DateTime dt =course.DateTaken.Date;
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken == dt &&
a.SymNumber == symNumber
select a;
if a.DateTaken contains Time also, then refer these links to modify your date.
The Date property cannot be used in LINQ To Entities.
Compare Dates using LINQ to Entities (Entity Framework)
'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
http://forums.asp.net/t/1793337.aspx/1
This is how I ended by doing a similar Date search which I had to consider time (Hour and Minutes portion) also
from x in _db.AgentProductTraining
where
x.CreatedOn.Year == mydacourse.DateTakente.Year
&& x.CreatedOn.Month == course.DateTaken.Month
&& x.CreatedOn.Day == course.DateTaken.Day
&& x.CreatedOn.Hour == course.DateTaken.Hour
&& x.CreatedOn.Minute == course.DateTaken.Minute
select x;
Hey when I was building a query this below worked
DateTime date = Convert.ToDateTime(SearchText);
query = query.Where(x => x.Date.Month == date.Month
&& x.Date.Day == date.Day
&& x.Date.Year == date.Year);
// Let me know if this worked for you as it pulled the date that was searched for me
Take off the .Date
If the field is a DateTime it can be compared with ==
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken == course.DateTaken &&
a.SymNumber == symNumber
select a;

Linq Subquery Where Clause

I need some help with thsi linq query. It shoudl be fairly simple, but it is kicking my butt.
I need to use a subquery to filter out data from the main query, but every path I have tried to use results in failure.
The subquery by itself looks like this.
int pk = (from c in context.PtApprovedCertifications
where c.FkosParticipant == 112118 &&
(!excludedActionTypes.Contains(c.FkMLSosCodeActionType)) &&
c.EffectiveDate <= DateTime.Now &&
c.FkptApprovedCertificationVoidedBy == null
orderby c.EffectiveDate descending,c.PK descending
select c.PK).FirstOrDefault();
This works as expected but as you can see I plugged in the number 112118. This should be the primary key from main query.
The combined query I've been working on looks like this.
IQueryable<PtAMember> result = (from p in context.PtAMembers
where (p.FkptACertification == (from c in context.PtApprovedCertifications
where c.FkosParticipant == p.PtApprovedCertification.OsParticipant.PK &&
(!excludedActionTypes.Contains(c.FkMLSosCodeActionType)) &&
c.EffectiveDate <= DateTime.Now &&
c.FkptApprovedCertificationVoidedBy == null
orderby c.EffectiveDate descending, c.PK descending
select c.PK).FirstOrDefault()) &&
(p.LastName.ToLower().Contains(param.ToLower()) ||
p.FirstName.ToLower().Contains(param.ToLower()) ||
p.SocialSecurityNumber.Contains(param))
select p).Distinct().OrderBy(PtAMembers => PtAMembers.LastName).ThenBy(PtAMember => PtAMember.FirstName);
This results in an error though. Any help in solving this conundrum would greatly appreciated.
Thanks!
How about turning your subquery into a lookup function:
Func<int, int> pkLookup = n => (from c in context.PtApprovedCertifications
where c.FkosParticipant == n &&
(!excludedActionTypes.Contains(c.FkMLSosCodeActionType)) &&
c.EffectiveDate <= DateTime.Now &&
c.FkptApprovedCertificationVoidedBy == null
orderby c.EffectiveDate descending,c.PK descending
select c.PK).FirstOrDefault();
then using that in your main query.

Resources