LINQ Multiple Filtering Fastest Way - c#

This Code will be called through the object data source within the asp.net application.
In northwind database , there exist a table with name of Customer. so I want to filter the grid view like below :
as you can see in image above , there are two drop downs at top of the grid view . they will filter the Gridview with ContactTitle and Country Columns , So , I have written the code In DAL Like Below :
var q = (from customers in db.Customers
select new
{
customers.ContactName,
customers.ContactTitle,
customers.City,
customers.Country,
customers.Phone,
customers.Address
});
if (!country.Equals("All")) q = q.Where(e => e.Country == country);
if (!contactTitle.Equals("All")) q = q.Where(e => e.ContactTitle == contactTitle);
So the code works nice , but this code will call the database connection three times ! One for selecting all , Second for filtering country and third Time for filtering with contact Title , How Can I Optimize this queries into One query ?
My Second Question is : How Can I Delete Duplicated Values in Drop downs with out querying again ? I don't want to use select Distinct or other query .... Can I have something like this :
(Note DropDowns are Binded to database...)
OnDataBind (e) {
if(!DropDown1.Contains(e.value)) DropDown1.Add(e.Value);
}
UPDATE :
var q = (from customers in db.Customers
where (country.Equals("All") || customers.Country == country ) &&
(contactTitle.Equals("All") || customers.ContactTitle == contactTitle)
select new
{
customers.ContactName,
customers.ContactTitle,
customers.City,
customers.Country,
customers.Phone,
customers.Address
});
The code above will do the same but not faster , because the first code is Linq To Object !

Related

How to apply Not In Linq?

I have tow tables - OrderRequisition and Order. I can show all the records from OrderRequisition table using linq query:
var list = (from r in db.OrderRequisition
select new SalesOrderViewModel
{
OrderId = r.OrderId ,
OrderNo = r.OrderNo
}).ToList();
I want to show only those records from OrderRequisition table which are not included in Order table. Any clue
Thanks
Partha
A simple approach that might be efficient enough because your database is able to optimize it:
var list = db.OrderRequisition
.Where(or => !db.Order.Any(o => o.OrderId == or.OrderId))
.ToList();
(skipped the SalesOrderViewModel initialization because not relevant for the question)

Searching with control in asp.net using where clause

I'm creating a product search where users can search base of what they want or simply choose Any which means it will display all product.
since I'm searching based on what is in the dropdownList control, if user choose a product category i have query the database to display the product in that category. How can i query the database to display product in all category when the user select 'Any' from the dropdownList.
When you prepare your query include a IF
This is pseudo code, because Im not sure how you store the values in the combo or how you make your sql consult. So is just to give you the general idea.
if( dropdwonList.SelectedItem.Value == "any" ) {
select * from products ;
}
else {
select * from products where categoryID = dropdwonList.SelectedItem.Value;
}
Or use this query
SELECT *
FROM products
WHERE
( categoryID = ddCategory.SelectedItem.Value
OR ddCategory.SelectedItem.Value= -1 // `-1` is your ID for `ANY`
) AND
( modelID = ddModel.SelectedItem.Value
OR ddModel.SelectedItem.Value= -1
) AND ....

Linq To Entities, Select multiple sets of data with one query

I've found plenty of info on how to select multiple result sets with stored procedures but nothing substantial on how to do so with a linq query.
For example, I can do sub-queries that return mulitple sets of results with something like
var query = (from school in context.Schools
where school.id == someId
select new
{
subSetA = (from student in context.Students
select student).ToList(),
subSetB = (from building in context.Buildings
select building).ToList(),
}).First();
query.subSetA; //Access subSetA
query.subSetB; //Access subSetB
Which works fine, but what if I just want to select both subSetA and subSetB without querying against the school table? I want to select two separate sets of data that gets sent to the server in one query.
Any information as to how to do this with EF 6 would be great.
Well, I'm sure there are many ways to do this, but if you want to avoid introducing a third DbSet into the mix...
var query = (from s in context.Students.Take(1)
select new
{
subSetA = context.Students.ToList(),
subSetB = context.Buildings.ToList(),
})
Then, you can use query.ToList() or maybe using query.Load() and working with context.Students.Local, etc. would work.

Linq-To-Entities 'Contains' clause 1-many relationship

Consider a (simplified) table structure like this:
[USERS]
EMPID
NAME
[APPOINTMENTS]
(FK_APPT_USER) EMPID
APPTTYPEID
COMPLETE
Each user can have 0..* appointments, each of which can be one of many APPTYPEID's, and can either be complete or not complete.
I want to filter the result set of a IQueryable[USER] query such that it only includes USERS who have an appt of some typeID (say 1) and where the COMPLETE field is in a list of values. I'm doing this as part of a gridview filter that allows users to select either to show only completed or not completed users for particular appointment types.
List<string> vals = new List<string> {"Y","N"}
//maybe the user has only selected Y so the above list only contains 1 element
var qry = ctx.USER.Where(x=> vals.Contains( ? ));
//bind etc
This is really easy to do if the values I'm comparing against the list are in a 1-1 relationship with the USER object, for example:
var qry = ctx.USER.Where(x=> vals.Contains(x.NAME));
But I don't understand how to do it with a 1-many relationship like with my appointments table, it's getting me all brain-tied trying to conceptualize the entity sql for it. Can anybody explain how to do this?
qry = ctx.USER.Where(u => u.APPOINTMENTS
.Where(a => a.APPTYPEID == 1)
.Any(a => vals.Contains(a.COMPLETE)));
UPDATE (added returning those users, which do not have appointments at all)
qry = ctx.USER.Where(u =>
!u.APPOINTMENTS.Any() ||
u.APPOINTMENTS.Any(a => a.APPTYPEID == 1 && vals.Contains(a.COMPLETE)));

LINQ query not showing in DGV

I have been researching this for some time, so if I missed a topic somewhere please point me in the right direction and accept my apologies.
I am performing a LINQ query on an incoming DataTable and setting up new columns based on the filtering done. The information being passed in is a single row containing the columns: CompanyName, CustomerID, LastName, FirstName, ContactTitle.
My question is, am I over-filtering the information to the point where it will return nothing to the DGV, or have I done something else wrong?
What I am trying to do is query another table based on the information passed in from the DataTable. Here is my query:
var query = (from id in IncomingOrderDetails.AsEnumerable()
from o in db.Orders
from c in db.Customers
from r in db.Regions
where (id.Field<int>("OrderID") == o.OrderID)
where (o.CustomerID == c.CustomerID)
where (c.Region == r.RegionDescription)
select new
{
CustomerID = c.CustomerID,
CompanyName = c.CompanyName,
ContactName = c.ContactName,
RegionDescription = r.RegionDescription,
Country = c.Country,
Phone = c.Phone
}).ToList();
custInfoDGV.DataSource = query;
This line:
where (c.Region == r.RegionDescription)
...looks dubious. If c.Region = r.RegionDescription, why do you need to bring in r at all? All you use it for is retrieving the RegionDescription.
I don't know your tables, but joining two fields that don't match would certainly produce 0 records returned. :)

Categories