How can I handle null values in some of the fields when populating the IQueryable table from the db? PetIDTag can have nulls.
IQueryable<PetTable> petIQ= from s in _context.PetT select s;
if (!String.IsNullOrEmpty(searchString))
{
petIQ = _context.PetT
.Where(x => x.PetName.ToString() == searchString)
.Select(s => new PetTable
{
PetName = s.PetName,
PetAddress = s.PetAddress,
PetIDTag = s.PetIDTag.Where(x => s.PetIDTag != null)
});
}
Calling .Where() on a single value doesn't make sense.
If you want to filter your entire query, add that to the query's Where().
Related
I want to query from Users table with linq query. I am getting an error on this line on "Users.Where";
var KisiList = Users.Where(w => w.Userstatus == 1 && w.Isactive == 1).ToList();
Users does not contain a definiton for where. what should I add here?
public List<Users> GetBagliOlduguKisiList()
{
var KisiList = Users.Where(w => w.Userstatus == 1 && w.Isactive == 1).ToList();
List< Users> users= new List< Users>();
foreach (var item in KisiList )
{
Users par= new Users();
par. ID= item. ID;
par. Name= item. Name;
users.Add(par);
}
return users;
}
Probably you have missed using System.Linq;. Also if you are using LINQ, try to do that effectively and retrieve only needed fields.
public List<Users> GetBagliOlduguKisiList()
{
var users = Users
.Where(w => w.Userstatus == 1 && w.Isactive == 1)
.Select(u => new Users
{
ID = u.ID,
Name = u.Name
})
.ToList();
return users;
}
I would like to have a single LINQ to SQL query to count 2 entities from the same table. E.g. Count number of employees and managers from table Personnel.
Example:
var q = from p in db.Personnel
where p.PersonType == 'Manager' || p.PersonType == 'Employee'
select new
{ NoOfPersonnel = p.Count(p => p.PersonType == 'Employee'), //Wrong way
NoOfManagers = p.Count(p => p.PersonType == 'Manager') //Wrong way
}
How can I do it?
Try this:
var list = from employee in db.Personnel
where employee.PersonType == "Manager" || employee.PersonType == "Employee"
group employee by employee.PersonType
into temp
select new { PersonType = temp.Key, Count = temp.Count() };
I have this:
var q = (from order in db.Orders
from payment in db.Payments
.Where(x => x.ID == order.paymentID)
.DefaultIfEmpty()
from siteUser in db.SiteUsers
.Where(x => x.siteUserID == order.siteUserID)
.DefaultIfEmpty()
where siteUser.siteUserID != null
select new
{
order.orderID,
order.dateCreated,
payment.totalAmount,
siteUser.firstName,
siteUser.lastName
});
I want to add on to it like this:
switch (_qs["sort"])
{
case "0":
q = q.OrderByDescending(x => x.dateCreated);
break;
case "1":
q = q.OrderBy(x => x.dateCreated);
break; ...
I've done this before with a single table, but the multiple tables in the first code block force me to specify a select statement which causes it to be an anonymous type. How can this be done?
Note: I even tried to make a class with the properties that i'm selecting and casting the query to this type, still a no go.
Not sure I understand the question but the code you pasted looks valid to me.
I checked:
var q = (
from order in db.Orders
join payment in db.Payments on
order.paymentID equals payment.ID into payments
from payment in payments.DefaultIfEmpty()
join siteUser in db.SiteUsers on
order.siteUserID equals siteUser.siteUserID into siteUsers
from siteUser in siteUsers.DefaultIfEmpty()
where siteUser.siteUserID != null
select
new
{
order.orderID,
order.dateCreated,
payment.totalAmount,
siteUser.firstName,
siteUser.lastName
});
switch (sort)
{
case "0":
q = q.OrderByDescending(x => x.dateCreated);
break;
case "1":
q = q.OrderBy(x => x.dateCreated);
break;
}
var restult = q.ToList();
This works.
I am really new to Linq and am using Linq-to-Sql as follows. However in the following example, my where clause never gets executed and the resultant query attempts to fetch all the records from my table, ignoring even the take method.
Can somebody point out as to what i am doing wrong
var baseQry = db.Table;
baseQry.Where(a => a.tab_id == theId);
baseQry.Select(o => new
{
o.name,
o.display_name,
o.type,
o.info,
time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
}).Take(10);
baseQry.ToList();
Your second line...
baseQry.Where(a => a.tab_id == theId);
...is essentially a no-op, because the resulting query isn't carried over into your .Select clause.
You need to change it to this:
var baseQry = db.Table;
var results = baseQry
.Where(a => a.tab_id == theId)
.Select(o => new
{
o.name,
o.display_name,
o.type,
o.info,
time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
})
.Take(10)
.ToList();
Is there any way to refactor this code so that it can omit unnecessary WHEREs and JOINs if the values passed into the function are null (this code works just fine right now if all parameters are passed in)? The "SearchItems" and "ItemDistance" functions are table-level functions for performing fulltext search and distance calculations, respectively.
public IQueryable<ItemSearchResult> Search(string keywords, int? category, float? latitude, float? longitude)
{
return from item in _db.Items
join searchItems in _db.SearchItems(keywords)
on item.ItemId equals searchItems.ItemId
join itemDistance in _db.ItemDistance(latitude.Value, longitude.Value)
on item.ItemId equals itemDistance.ItemId
where item.Category == category.Value
select new ItemSearchResult()
{
Item = item,
Distance = itemDistance.Distance
};
}
I'm making the assumption that if either of latitude or longitude is not provided, you don't calculate the distance (I'd probably encapsulate both into a class and pass that instead of passing separately to avoid confusion). If one or the other is not provided, the default Distance is used for the search result.
public IQueryable<ItemSearchResult> Search(string keywords, int? category, float? latitude, float? longitude)
{
IEnumerable<ItemSearchResult> result = null;
var query = _db.Items.AsEnumerable();
if (category.HasValue)
{
query = query.Where( i => i.Category == category.Value );
}
if (!string.IsNullOrEmpty(keywords))
{
query = query.Where( i => _db.SearchItems(keywords)
.Any( s => s.ItemId == i.ItemId ));
}
if (latitude.HasValue && longitude.HasValue)
{
result = from item in query
join distance in _db.ItemDistance( latitude.Value, longitude.Value )
on item.ItemId equals distance.ItemId
select new ItemSearchResult
{
Item = item,
Distance = distance.Distance
};
}
else
{
result = query.Select( i => new ItemSearchResult { Item = i } );
}
return result != null
? result.AsQueryable()
: new List<ItemSearchResult>().AsQueryable();
}
For starters, the only value passed into that function that can be null is keywords, as all others are non-nullable value types. So I'll consider that only (if you need it, others can be treated similarly).
Just don't use joins in the first place:
return from item in _db.Items
where keywords == null || _db.SearchItems(keywords).Select(si => si.ItemId).Contains(item.ItemId) &&
...
where item.Category == category
select new ItemSearchResult()
{
Item = item,
Distance = itemDistance.Distance
};