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
Related
OK, this doesn't work due to Azure Table query subset constraints:
var res = tcmarketnlog.Where(t => t.Level == level && t.Message.Contains("151207151510") && t.Timestamp >= start && t.Timestamp <= end).Take(1000);
The t.Message.Contains("151207151510") bombs. However, there must be some way to then search the results in LINQpad and select only the results with this string in the message.
For example, I could not coerce the result into a variable that was then queriable again with LINQ. Any tips?
If you can't use string.Contains on an Azure Table Queryable, you can still turn it into an Enumerable and then apply the additional filter to only show the results you want. However, it means that it will return all records that meet the other criteria over the network before then limiting them on the client side to only those rows where the Message field contains the specified string.
var res = tcmarketnlog.Where(t => t.Level == level && t.Timestamp >= start && t.Timestamp <= end).AsEnumerable().Where(t => t.Message.Contains("151207151510")).Take(1000);
Maybe message is null. Just check message null before contains. pls try this:
var res = tcmarketnlog.Where(t => t.Level == level
&& t.Message != null && t.Message.Contains("151207151510")
&& t.Timestamp >= start && t.Timestamp <= end).Take(1000);
I have a LINQ query which works fine as for stand alone lists but fails for CRM
var lst = new List<bool?>();
lst.Add(null);
lst.Add(true);
lst.Add(false);
bool IsWet = false;
var newlst = from exch_HideVoiceSignature in lst where
(((exch_HideVoiceSignature!=null && exch_HideVoiceSignature==false
|| exch_HideVoiceSignature== null) )&& !IsWet) select exch_HideVoiceSignature;
newlst.Dump();
var question = from q in exch_questionSet where ((q.exch_HideVoiceSignature != null
&& q.exch_HideVoiceSignature.Value == 0 )|| q.exch_HideVoiceSignature == null )
&& !IsWet select q.exch_HideVoiceSignature;
question.FirstOrDefault().Dump();
As you can see I can pass the variable IsWet to LINQ query for a standard list fine and get values for first list. But when I execute the same for second list, I get the following error
Invalid 'where' condition. An entity member is invoking an invalid property or method
The CRM LINQ provider won't support the evaluation you attempting. It only supports evaluation of where criteria is evaluating an entity field.
That's not a problem. Since you want the LINQ query to only use the where clause if IsWet is false (correct me if I'm wrong on that.) So we simply do the evaluation to determine if the where clause should be added or not. Then execute your query.
var question = from q in exch_questionSet
select q.exch_HideVoiceSignature;
if (!IsWet)
{
question.Where(x => ((x.exch_HideVoiceSignature != null
&& x.exch_HideVoiceSignature.Value == 0) || x.exch_HideVoiceSignature == null));
}
question.FirstOrDefault().Dump();
I am constantly confronted with that problem.
Try to "detach" (for example call .ToArray()) your query (while it is "clear") from CRM and then filter query using external parameter. This should help.
var question =
(from q in exch_questionSet
where (
(q.exch_HideVoiceSignature != null && q.exch_HideVoiceSignature.Value == 0 ) ||
q.exch_HideVoiceSignature == null )
select q.exch_HideVoiceSignature
).ToArray().Where(q => !IsWet);
question.FirstOrDefault().Dump();
UPDATE
If you are using IsWet flag to control blocks of conditions (enable and disable them from the one point in the code) then probably you may be interested in class named PredicateBuilder which allows you to dynamically construct predicates.
Just because I had an existing query with lot of other joins etc. and I wanted to pass this additional parameter to it I ended up using a var statement which dumps the rows to a list and applies the where clause in the same statement
bool IsWet =true ;
var question = ...existing query ...
select new {
...existing output ...,
Wet =q.exch_HideVoiceSignature != null &&
q.exch_HideVoiceSignature.Value == 119080001,
Voice = q.exch_HideVoiceSignature == null ||
(q.exch_HideVoiceSignature != null &&
q.exch_HideVoiceSignature.Value == 119080000) ,
}
;
var qq = IsWet ?
question.ToList().Where(X=> X.Wet ) :
question.ToList().Where(X=> X.Voice );
qq.FirstOrDefault().Dump();
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;
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);
I tried to use the suggestion provided here for using In operator in linq but, i am not able to convert my requirement into LINQ statement.
Below is the SQL query which i need to convert to Linq
select *
from navigator_user_field_property
where user_id = 'albert'
and field_id in (
select field_id
from navigator_entity_field_master
where entity_id = 1
and use_type = 0)
order by field_id
I want this to be converted to a Efficient Linq.
Most of the answers deal with the predetermined list of string array which is not working in my case.
Thanks
Looks like a join to me:
var query = from navigator in db.NavigatorUserFieldProperties
where navigator.UserId == "albert"
join field in db.NavigatorEntityFieldMasters
.Where(f => f.EntityId == 1 && f.UseType == 0)
on navigator.FieldId equals field.FieldId
select navigator;
Note that this will return the same value multiple times if there are multiple fields with the same ID - but I suspect that's not the case.
You could do a more literal translation like this:
var query = from navigator in db.NavigatorUserFieldProperties
where navigator.UserId == "albert" &&
db.NavigatorEntityFieldMasters
.Where(f => f.EntityId == 1 && f.UseType == 0)
.select(f => f.FieldId)
.Contains(navigator.FieldId)
select navigator;
... and that may end up translating to the same SQL... but I'd personally go with the join.
Here is an efficient and readable LINQ query:
var fields =
from field in db.navigator_entity_field_masters
where field.entity_id == 1 && field.user_type == 0
select field;
var properties =
from property in db.navigator_user_field_properties
where property.user_id == "albert"
where fields.Contains(property.field)
select property;
Look mama!! Without joins ;-)