ASP.NET IQueryable WHERE OR - asp.net

I am trying to write this piece of code that will search the database table and I am trying to search multiple columns. What I have below appears to be the equivalent to WHERE column = "this" AND column2 = "this", what I am trying to do is this WHERE column = "this" OR column2 = "this" How would I accomplish this?
query = query.Where(p => (p.ChckNumber.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.BankAccount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.Description.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.CheckAmount.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.ClearedDate.ToString()).Contains(globalSearch.ToString()));
query = query.Where(p => (p.SentDate.ToString()).Contains(globalSearch.ToString()));

You should be able to do this in-line using the OR operator:
query = query.Where(p =>
p.ChckNumber.ToString().Contains(globalSearch.ToString()) ||
p.BankAccount.ToString().Contains(globalSearch.ToString()) ||
p.Description.ToString().Contains(globalSearch.ToString()) ||
p.CheckAmount.ToString().Contains(globalSearch.ToString()) ||
p.ClearedDate.ToString().Contains(globalSearch.ToString()) ||
p.SentDate.ToString().Contains(globalSearch.ToString())
);

Related

Core EF Outer Join,Count & Group

I'm trying to convert this SQL Query into Core EF:
SELECT w.IdShippingBatch, w.BookingNumber, COUNT(c.IdShippingOrder) AS ShippingOrders, w.CreatedOn, w.ModifiedOn
FROM dbo.Shipping`enter code here`Batch AS w LEFT OUTER JOIN
dbo.ShippingOrders AS c ON w.IdShippingBatch = c.IdShippingBatch
WHERE (w.IdCompany = 2) AND (w.IdDealer = 1)
GROUP BY w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn
I have tried multiple solutions, including several here. My latest attempt looks like:
var data = (from w in _context.ShippingBatch
join c in _context.ShippingOrders on w.IdShippingBatch equals c.IdShippingBatch into t1
where w.IdCompany == idCompany && w.IdDealer == idDealer
from t2 in t1.DefaultIfEmpty()
group t2 by new { w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn } into t3
select new ShippingBatchDTO
{
IdShippingBatch = t3.Key.IdShippingBatch,
BookingNumber = t3.Key.BookingNumber,
ShippingOrders = t3.Count(),
CreatedOn = t3.Key.CreatedOn,
ModifiedOn = t3.Key.ModifiedOn
});
I have also tried adding t3.count(m => m.something != null), but that throws an error.
One major point of EF is to map the relationship between entities so that you can leverage LINQ and let EF compose an SQL query rather than trying to replace SQL with LINQ-QL.
If your ShippingBatch is mapped with a collection of ShippingOrders...
var batches = _context.ShippingBatch
.Where(x => x.IdCompany == idCompany && x.IdDealer == idDealer)
.Select(x => new ShippingBatchDTO
{
IdShippingBatch = x.IdShippingBatch,
BookingNumber = x.BookingNumber,
ShippingOrders = x.ShippingOrders.Count(),
CreatedOn = x.CreatedOn,
ModifiedOn = x.ModifiedOn
}).ToList();
If your ShippingBatch does not have a collection of ShippingOrders, but your ShippingOrder reference an optional ShippingBatch.
var batches = _context.ShippingOrder
.Where(x => x.ShippingBatch != null
&& x.ShippingBatch.IdCompany == idCompany
&& x.ShippingBatch.IdDealer == idDealer)
.GroupBy(x => x.ShippingBatch)
.Select(x => new ShippingBatchDTO
{
IdShippingBatch = x.Key.IdShippingBatch,
BookingNumber = x.Key.BookingNumber,
ShippingOrders = x.Count(),
CreatedOn = x.Key.CreatedOn,
ModifiedOn = x.Key.ModifiedOn
}).ToList();
That should hopefully get you moving in the right direction. If not, expand your question to include details of what you are seeing, and what you expect to see along with definitions for the applicable entities.

In one Linq Query get back data from multiple tables

I have 3 tables:
sessions - This store information about trainings
xref_session_faculty - This cross references the trainings and the teacher
user - list of all teachers
In one(or more) LINQ query i want to get all the sessions and for each session the teachers that will be conducting the training. Each session can have zero or more teachers in the DB.
sessions = db.sessions
.Where(x => x.seminar_id == seminarId)
.ToList()
.Select((x, i) => new fees
{
id = x.id,
sessionTitle = x.title,
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).ToList()
)
)
})
.ToList();
With this the teacherNames prints out By:System.Collections.Generic.List1[System.String],System.Collections.Generic.List1[System.String].
WHat is the right query format here?
teacherNames = "By:" + String.Join(",",
x.xref_session_faculty.ToList()
.Select(q => db.users
.Where(m => m.id == q.user_id)
.Select(t => t.firstName).FirstOrDefault()
)
)
you need to change ToList to FirstOrDefault function to get correct result
private var sessions = (from session in db.sessions.Where(x => x.seminar_id == seminarId)
select new
{
id = session.id,
sessionTitle = session.title,
teacherNames = (from faculty in db.xref_session_faculty.
where (x => x.session_id == session.id)
join us in db.uses on faculty.user_id equals us.user_id
select new
{
us.firstName,
other_field_names
})
});

How to check null in lambda expression

How to check for null in where condition in lambda expression?
listdropdownid.Id = listgroupid.Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();
listdropdownid.Desc = desc;
If abc == desc fails, I need to assign null to listdropdownid.Id.
The most elegant way is to specify another default value using DefaultIfEmpty(newValue):
listdropdownid.Id = listgroupid
.Where(x => x.abc == desc)
.Select(x => x.abc_id.ToString())
.DefaultIfEmpty(null) // would be more useful if you'd provide a more meaningful value like "<not found>"
.First;
That works even with value types, in this case you could also use FirstOrDefault since the default value of string is already null. You just have to select it:
listdropdownid.Id = listgroupid
.Where(x => x.abc == desc)
.Select(x => x.abc_id.ToString())
.FirstOrDefault();
This should help you:
listdropdownid = listgroupid.Where(X => X.abc == desc).FirstOrDefault();
if (listdropdownid != null)
{
// Do something with listdropdownid.Id
}
do this
listdropdownid.Id = listgroupid.Where(X=>X!=null).Where(X => X.abc == desc).FirstOrDefault().abc_id.ToStr();

using select in datatable

My Datatable is in following format.
I want to get the Netfare Where Sector is 1 and then similarly I want to get Netfare Where Sector is 2.
Thanks
You can use the DataTable.Select method to filter the result.
var sector1Results = dt.Select("Sector = 1");
var sector2Results = dt.Select("Sector = 2");
You can also use DataTable.AsEnumerable method to achieve the same
var result1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).Select(x => x.Field<int>("Sector1"));
var result2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 2).Select(x => x.Field<int>("Sector2"));
To select the DataRow collection, You can use this
List<DataRow> collection1 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
List<DataRow> collection2 = dt.AsEnumerable().Where(x => x.Field<int>("Sector") == 1).ToList();
You can also merge those condition in single statement (if you want)
List<DataRow> collection = new DataTable().AsEnumerable().Where(x => x.Field<int>("Sector") == 1 || x.Field<int>("Sector") == 2).ToList();

Dynamic Linq for dates

I want to build dynamic Linq. Following is my code which works fine for one date. But user can select many dates from calendar. And I need to make Linq for all those selected dates.
saleDate = calendarSales.SelectedDate;
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => (Convert.ToDateTime(sale.DATE_TIME).Day == saleDate.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == saleDate.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == saleDate.Year)
).ToList();
How to update this query?
You have to build the predicate for your where clause dynamically.
Take a look at the predicatebuilder.
EDIT
Of cause PredicateBuilder supports AND and OR operators.
When using OR you have to start with the initial value of False:
// building the predicate
var pred = PredicateBuilder.False<SaleDetails>();
foreach (var date in MyDateList)
{
pred = pred.Or(sale => sale.DATE_TIME.Date == saleDate.Date);
}
// finally get the data and filter it by our dynamic predicate
List<SaleDetails> saleDetails = GetSaleDetails().Where(pred).ToList();
I'm not sure you need dynamic LINQ here. You should be able to check Where the sale matches Any of the selected dates, like so:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
(Convert.ToDateTime(sale.DATE_TIME).Day == date.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == date.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == date.Year)
)).ToList();
or checking on the Date property:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
Convert.ToDateTime(sale.DATE_TIME).Date == date.Date)).ToList();

Resources