LINQ query records based on date array - linq-to-sql

I have a table (I am using Entity Model) and filtered that table using LINQ query which is working fine.
Now I want to filter the records on the basis of array of dates. I am not able to implement IN clause on array of dates
filteredList = leadsNewAndScheduled.Where(lead =>
(LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
LeadTypeIDs == string.Empty) &&
(priorityIDs.Contains(lead.PRIORITY_ID.ToString()) ||
priorityIDs == string.Empty) &&
(((lead.EXPIRED_ON <= dateExpiry ||
Convert.ToDateTime(lead.EXPIRED_ON) == DateTime.Today.Date) &&
lead.STATUS_ID == (int)Enumerations.LeadStatus.New) ||
lead.STATUS_ID == (int)Enumerations.LeadStatus.Active) &&
(lead.START_TIME IN (arrAppointmentDates))
).ToList();
I want your help in following
(lead.START_TIME IN (arrAppointmentDates))
Thanks in advance.

Use Predicate Builder
Write your query without the date condition like
var query = leadsNewAndScheduled.Where(lead =>
(LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
LeadTypeIDs == string.Empty) && ....
Then write
var predicate = PredicateBuilder.False<Lead>();
foreach (DateTime date in dates)
{
DateTime temp = date;
predicate = predicate.Or (p => p.START_TIME == temp);
}
var result = query.Where(predicate).ToList(); // Don't call ToList() earlier
However please note that if you're using Entity Framework you need to call AsExpandable() on the entity set before applying predicates on it like so:
return objectContext.Products.AsExpandable().Where (predicate);

I solved this problem while declaring list of dates and then applying contains clause in LINQ query.
example:
//list of dates.
List<DateTime> arrAppointmentDates;
//change in query
arrAppointmentDates.Contains(Convert.ToDateTime(lead.START_TIME).Date)

Related

Use Conditional Split for multiple empty string

I have a scenario where I am generating two .CSV files from one .TXT file source.
One of the transformations required is this:
Identify records that contain at least one field with an empty string or NULL value
Send these records to a separate .CSV file destination
I need to check for this condition across multiple fields.
For example I have these fields in my source .TXT file:
col1
col2
col3
col4
col5
col6
col7
I need to check to see if any of these fields contain an empty string or a NULL value.
I am using a Conditional Split Transformation with this formula:
col1 !=""
That works as expected for one column, but not as expected when I try to write the formula for all columns in my text file:
col1 !="" || col2 !=""...
Some rows with an empty or NULL value in one of the fields are ending up in the wrong .CSV file.
Any help is appreciated!
If I have understood your question correctly, I think you just need to use the following formula in a Conditional Split Transformation:
ISNULL(col1) || ISNULL(col2) || ISNULL(col3) || ISNULL(col4) || ISNULL(col5) || ISNULL(col6) || ISNULL(col7) || TRIM(col1) == "" || TRIM(col2) == "" || TRIM(col3) == "" || TRIM(col4) == "" || TRIM(col5) == "" || TRIM(col6) == "" || TRIM(col7) == ""
There is a difference between an empty string and a NULL, although since your source is a .TXT file this might not be so obvious as it would be if your source was a database table.
Here is the SQL Fiddle for the sample data.
Screenshot of the Conditional Split Transformation Editor
Screenshot of the Data Flow results
Hope this helps.
I Figured it out. Used script component before conditional split to flag the rows.
Code:
/* Microsoft SQL Server Integration Services Script Component
* Write scripts using Microsoft Visual C# 2008.
* ScriptMain is the entry point class of the script.*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
/**string RecordID = "";
string ClientRequestID = "";
string AccountID = "";
string ClientMemberID = "";
string MemberDOB = "";
string ProviderPhone = "";**/
string Flag = "True";
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
if (Row.ClientRequestID == "" || Row.ClientMemberID == "" || Row.AccountID == "" || Row.MemberDOB == "" || Row.ProviderPhone == "")
{
Flag = "False";
}
else
{
Flag = "True";
}
Row.Flag = Flag;
}
}

Named query with optional parameter not working in mysql

I have a named query below for optional parameter which is flightNumber, departureAirport and arrivalAirport. But this query is not working when I don't give any value for these parameter.
#Query("from CapacityMonitor
where carrierCode = :carrierCode and
(:flightNumber IS NULL OR flightNumber = :flightNumber) and
(:departureAirport IS NULL OR departureAirport = :departureAirport) and
(:arrivalAirport IS NULL OR arrivalAirport = :arrivalAirport)
I can change a query but i have to use with #Query annotation only
So you want to keep your query the way it is and make it work with or without parameters. Well, you can't do that. If the query is expecting parameters, then you have to set them.
The best approach would be to leave the query the same way it is and set the parameters to NULL so that :param IS NULL returns TRUE in those cases and return all results. That way you will fake a match.
Anyway, the parameter has to be set always.
I would suggest using a Criteria Query to build a statement with custom WHERE clause.
Based on your example, it could look like this (depending on your data types):
public List<CapacityMonitor> getFlights(String carrierCode, String flightNumber, String departureAirport, String arrivalAirport) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<CapacityMonitor> query = builder.createQuery(CapacityMonitor.class);
Root<CapacityMonitor> root = query.from(CapacityMonitor.class);
query.select(root);
// Carrier code is mandatory
query.where(builder.equals(root.get("carrierCode"), carrierCode));
// Other properties are optional
if (null != flightNumber && flightNumber.length() > 0) {
query.where(builder.equals(root.get("flightNumber"), flightNumber));
}
// Use LIKE expression to match partially
if (null != departureAirport && departureAirport.length() > 0) {
query.where(builder.like(root.get("departureAirport"), "%" + departureAirport + "%"));
}
if (null != arrivalAirport && arrivalAirport.length() > 0) {
query.where(builder.like(root.get("arrivalAirport"), "%" + arrivalAirport + "%"));
}
return em.createQuery(query).getResultList();
}

linq mysql : select multiple column and send the to view

I have selected multiple columns from my table, but I don't know how to pass it to my view.
var result = (from f in db.firmware
where f.firmware_release_type_text != ""
|| f.firmware_release_type_text != null
|| f.firmware_release_number_int != 0
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}).Distinct();
The result is f__anonymous2. I want to some how use it in my view. all the forums have just answered how to choose multiple columns, but nobody mentions how to pass them. I think I'm missing something obvious.
I want to be able to use this fields, or even merge them as one string.
I have tried Cast and so many other options which did not work.
When I try to force casting it sting, I get :
Unable to cast the type 'Anonymous type' to type 'System.String'
Thanks
UPDATE:
At the end I went with:
var result = (from f in db.firmware
where (f.firmware_release_type_text != "")
&& (f.firmware_release_type_text != null)
&& (f.firmware_release_number_int != 0)
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}
).Distinct();
List<string> result2 = new List<string>();
foreach (var item in result)
{
result2.Add(item.firmware_release_type_text
+ "-" + item.firmware_release_number_int);
}
If you want to return your data as a string you have to say how it should be formatted. You could for example change this:
select new
{
f.firmware_release_type_text , f.firmware_release_number_int
}
To this:
select f.firmware_release_type_text + " v" + (int)f.firmware_release_number_int
You have two options to create a model first, second format the data on the server side.

LINQ Query returns nothing

Why is this query returns 0 lines?
There is a record matching the arguments.
SomeDataContext db = new SomeDataContext(ConnString);
return db.Deafkaw.Where(p =>
(p.SomeDate1 >= aDate &&
p.SomeDate1 <= DateTime.Now) &&
(p.Year == aYear && p.IsSomething == false)
).ToList();
Am i missing something?
On the Table Deafkaw
SomeDate1 = 20/4/2010 11:32:17
Year = 2010
IsSomething = False
...besides other columns im not interested in conditions.
I need SomeDate1 between the dates i give IsSomething = False and Year = 2010.
You aren't assigning the result to anything so it is being discarded. Try this:
var results = db.Deafkaw.Where(p =>
(p.ImerominiaKataxorisis >= aDate &&
p.ImerominiaKataxorisis <= DateTime.Now) &&
(p.Year == etos && p.IsYpodeigma == false)
).ToList();
Update: you changed the question so now I'm not sure that this is the correct answer. Can you post the code where you call this method?
It is difficult to answer your question without any additional information. Checking the following points may help you to find the problem:
If you remove Where clause and write Deafkaw.ToList(), what do you get?
What is the value of aDate and etos?
Can you double check the condition? Do you require that all subconditions hold at the same time? Are there any such data if you print entire DeaFkaw data structure?
Can you try removing some sub-conditions to see if that gives you some results?
Try
Deafkaw.Where(p => (p.ImerominiaKataxorisis >= aDate && p.ImerominiaKataxorisis <= DateTime.Now &&
p.Year == etos && p.IsYpodeigma == false)).ToList();
Use SQL profiler. Look at the sql query that is generated. Run the sql query manually and see if you get back any records.

How do I use Count and Group in a select query in Linq?

I had the following Linq code:
var allRequests = model.GetAllRequests();
var unsatisifedRequests = (from request in allRequests
where request.Satisfied == false
select request)
.OrderBy(r => r.RequestedOn)
.GroupBy(r => r.RequestedCountryId);
After which I then did a foreach over unsatifiedRequests building a new TOARequestListSummary object for each. This meant if I "returned" 4 items from the query, it would make 4 calls to the DB, once per loop of the foreach to grab the individual rows.
This seems to be the wrong way to use Linq, so I tries to convert this query to one which used projections to return the TOARequestListSummary objects directly and I came up with:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountryId into requestGroups
select new TOARequestListSummary
{
CountryName = requestGroups.First().RequestedCountry.Description,
RequestCount = requestGroups.Count(),
FirstRequested = requestGroups.First().RequestedOn
});
But when I run this, I get the following exception:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
I have got as far as knowing that the Linq equivalent to EXISTS is Contains, but I have no idea how to indroduce this into the query.
This should work for you:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountry into g
select new TOARequestListSummary
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.Min(i => i.RequestedOn)
});
In your original version of this query (the second one you posted), your group's key was the RequestedCountryId. Though this will technically be grouping on that, you actually want to use the associated object. This way you'll have easy access to the needed properties and won't need to worry about grabbing the first item.
Sorry, this is an answer, rather than an additional comment to Ryan's answer, but it is too long to fit...
This gets very strange. In LinqPad the following works a treat:
from request in TOARequests
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}
But the following throws the same translation exception in C#
var summaries = (from request in context.Repository<TOARequest>()
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}).ToList();
The only difference I can see if the ToList(), but even without that when I try to enumerate the list, it throws the exception.