Unexpected behavior of the `Where` clause - c#

I have the following Linq statement which is used to retrieve the list of all rows in the table which satisfy a particular condition.
var set = db.TcSet
.Where(x => x.SetName.Equals(original.SetName))
.AsEnumerable()
.Where(x => x.SetName == original.SetName))
This particular statement is used to edit all entities in the table with a particular name. So the initial name of the property is retrieved in the original and checked for all other entries in the database which matches the condition.
Current Output
If I have two entries with the name Play123 and Edit one of the entry the output of the where query only contains one element.
If there is an entry Play123 and Play1234, and I try to edit Play123 to Play1234 , the output of the where query contains two elements : Play123 and Play1234 .
What am I missing that results in this unexpected behavior.
Update
var original = db.TcSet.Find(tcSet.TcSetID);
foreach (var set in db.TcSet
.Where(x => x.SetName.Equals(original.SetName))
.AsEnumerable()
.Where(x => x.SetName == original.SetName)))
{
if (set.SetName == original.SetName) // This was added again due to the unexpected behavior
{
set.ModifiedBy = User.Identity.Name;
set.ModifiedOn = DateTime.Now;
set.PhysicalUnit = tcSet.PhysicalUnit;
db.Entry(set).State = EntityState.Modified;
db.Entry(set).Property(x => x.CreatedBy).IsModified = false;
db.Entry(set).Property(x => x.CreatedOn).IsModified = false;
db.Entry(set).Property(x => x.TechnicalCharacteristicID).IsModified = false;
}
}
Now I have solved the problem by iterating through all the elements in the table which I know isn't the best practice.
Working code
var editlist = db.TcSet.Where(x => x.SetName == original.SetName).AsEnumerable().Where(x=>x.SetName==original.SetName).ToList();
foreach(var set in editlist)
// do save
When I removed the if condition it worked.

You want to do a case-insensitive check in your first .Where() clause, if you are to treat abc and ABC differently.
var set = db.TcSet
.Where(x => x.SetName.Equals(original.SetName, StringComparison.OrdinalIgnoreCase));
I would also suggest to cache the results before iterating in the foreach, as you are changing the source list while iterating through it which is never a good idea.
var original = db.TcSet.Find(tcSet.TcSetID);
var sets = db.TcSet
.Where(x => x.SetName.Equals(original.SetName, StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var set in sets)
{
set.ModifiedBy = User.Identity.Name;
set.ModifiedOn = DateTime.Now;
set.PhysicalUnit = tcSet.PhysicalUnit;
db.Entry(set).State = EntityState.Modified;
db.Entry(set).Property(x => x.CreatedBy).IsModified = false;
db.Entry(set).Property(x => x.CreatedOn).IsModified = false;
db.Entry(set).Property(x => x.TechnicalCharacteristicID).IsModified = false;
}

Related

EF Core Reuse subquery in different queries

I have a problem trying to reuse some subqueries. I have the following situation:
var rooms = dbContext.Rooms.Select(r => new
{
RoomId = r.Id,
Zones = r.Zones.Select(zr => zr.Zone),
Name = r.Name,
Levels = r.Levels.Select(lr => lr.Level),
IdealSetpoint = (double?)r.Group.Setpoints.First(sp => sp.ClimaticZoneId == dbContext.ClimaticZonesLogs.OrderByDescending(cz => cz.Timestamp).First().ClimaticZoneId).Setpoint??int.MinValue,
Devices = r.Devices.Select(rd => rd.Device)
}).ToList();
var tagsTypes = rooms.Select(r => r.Devices.Select(d => GetSetpointTagTypeId(d.DeviceTypeId))).ToList().SelectMany(x => x).Distinct().ToList();
predicate = predicate.And(pv => tagsTypes.Contains(pv.TagSettings.TagTypeId) &&
pv.ClimaticZoneId == dbContext.ClimaticZonesLogs.OrderByDescending(cz => cz.Timestamp).First().ClimaticZoneId);
var setpoints = valuesSubquery.Include(t=>t.TagSettings).Where(predicate).ToList();
This works fine, and generates the exact queries as wanted. The problem is that I want to have this subquery dbContext.ClimaticZonesLogs.OrderByDescending(cz => cz.Timestamp).First().ClimaticZoneId to be taken from a method and not repeat it every time I need it.
I've tested it with the database, where I have values in the corresponding tables, and I've tested the query with the database without any data in the corresponding tables. It works fine with no problems or exceptions.
But when I try to extract the repeating subquery in a separate method and execute it against empty database tables (no data) the .First() statement throws error. Here is the code:
protected long GetClimaticZoneId()
{
return dbContext.ClimaticZonesLogs.OrderByDescending(cz => cz.Timestamp).First().ClimaticZoneId;
}
and the query generation:
var rooms = dbContext.Rooms.Select(r => new
{
RoomId = r.Id,
Zones = r.Zones.Select(zr => zr.Zone),
Name = r.Name,
Levels = r.Levels.Select(lr => lr.Level),
IdealSetpoint = (double?)r.Group.Setpoints.First(sp => sp.ClimaticZoneId == GetClimaticZoneId()).Setpoint??int.MinValue,
Devices = r.Devices.Select(rd => rd.Device)
}).ToList();
var tagsTypes = rooms.Select(r => r.Devices.Select(d => GetSetpointTagTypeId(d.DeviceTypeId))).ToList().SelectMany(x => x).Distinct().ToList();
predicate = predicate.And(pv => tagsTypes.Contains(pv.TagSettings.TagTypeId) &&
pv.ClimaticZoneId == GetClimaticZoneId());
var setpoints = valuesSubquery.Include(t=>t.TagSettings).Where(predicate).ToList();
After execution I get InvalidOperationException "Sequence do not contain any elements" exception in the GetClimaticZoneId method:
I'm sure that I'm not doing something right.
Please help!
Regards,
Julian
As #Gert Arnold suggested, I used the GetClimaticZoneId() method to make a separate call to the database, get the Id and use it in the other queries. I gust modified the query to not generate exception when there is no data in the corresponding table:
protected long GetClimaticZoneId()
{
return dbContext.ClimaticZonesLogs.OrderByDescending(cz => cz.Timestamp).FirstOrDefault()?.ClimaticZoneId??0;
}

Joining table to a list using Entity Framework

I have the following Entity Framework function that it joining a table to a list. Each item in serviceSuburbList contains two ints, ServiceId and SuburbId.
public List<SearchResults> GetSearchResultsList(List<ServiceSuburbPair> serviceSuburbList)
{
var srtList = new List<SearchResults>();
srtList = DataContext.Set<SearchResults>()
.AsEnumerable()
.Where(x => serviceSuburbList.Any(m => m.ServiceId == x.ServiceId &&
m.SuburbId == x.SuburbId))
.ToList();
return srtList;
}
Obviously that AsEnumerable is killing my performance. I'm unsure of another way to do this. Basically, I have my SearchResults table and I want to find records that match serviceSuburbList.
If serviceSuburbList's length is not big, you can make several Unions:
var table = DataContext.Set<SearchResults>();
IQuerable<SearchResults> query = null;
foreach(var y in serviceSuburbList)
{
var temp = table.Where(x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId);
query = query == null ? temp : query.Union(temp);
}
var srtList = query.ToList();
Another solution - to use Z.EntityFramework.Plus.EF6 library:
var srtList = serviceSuburbList.Select(y =>
ctx.Customer.DeferredFirstOrDefault(
x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId
).FutureValue()
).ToList().Select(x => x.Value).Where(x => x != null).ToList();
//all queries together as a batch will be sent to database
//when first time .Value property will be requested

LINQ: How to Select specific columns using IQueryable()

I need to select only two columns from Hospital table, HospitalId and Name.
i tried the below code it selects all columns from Hospital table which lead to slow performance. Please help me to select only two columns from Hospital table
public HttpResponseMessage GetAvailableHospitalsByAjax(System.Guid? DirectorateOfHealthID = null, System.Guid? UnitTypeID = null, string DeviceTypeIDs = null)
{
Context db = new Context();
var query = db.Hospitals.AsQueryable();
if (UnitTypeID != null)
{
query = query.Where(j => j.HospitalDepartments.Any(www => www.Units.Any(u => u.UnitTypeID == UnitTypeID)));
}
if (DirectorateOfHealthID != null)
{
query = query.Where(h => h.DirectorateHealthID == DirectorateOfHealthID);
}
query = query.Where(j => j.HospitalDepartments.Any(u => u.Units.Any(d => d.Devices.Any(s => s.Status == Enums.DeviceStatus.Free)))
&& j.HospitalDepartments.Any(hd => hd.Units.Any(u => u.Beds.Any(b => b.Status == Enums.BedStatus.Free))));
var list = query.ToList().Select(w => new HospitalInfo()
{
Id = w.ID,
Name = w.Name
}).ToList();
return Request.CreateResponse(HttpStatusCode.OK, list);
}
IQueryable<T> executes select query on server side with all filters. Hence does less work and becomes fast.
IEnumerable<T> executes select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.
List<T> is just an output format, and while it implements IEnumerable<T>, is not directly related to querying.
So,
var list = query.ToList().Select(w => new HospitalInfo()
{
Id = w.ID,
Name = w.Name
}).ToList();
In your code you use query.ToList(). This means at first it pull all data into memory then apply Select query.If you want to retrieve HospitalID and Name then remove ToList() then your code like
var list = query.Select(w => new HospitalInfo
{
Id = w.ID,
Name = w.Name
}).ToList();
Remove the ToList call before the projection:
var list = query.Select(w => new HospitalInfo()
{
Id = w.ID,
Name = w.Name
}).ToList();
With that ToList call you are materializing your query before do the projection
Because you do query.ToList() this materialises the entire query with all columns into memory. It's actually a bad habit to get into. Instead, remove that, you already have it at the end anyway. The Select projection you have will only retrieve the relevant columns though:
var list = query.Select(w => new HospitalInfo()
{
Id = w.ID,
Name = w.Name
}).ToList();

Using Entity Framework dynamically sort by a column in a child

I call dynamically sort rows of a table when the orderby column is in the parent table doing the following...
public List<ServiceRequest> SortSRsByParentFields(string p_Criteria,
bool p_sortDescending,
bool p_ShowAll = true) {
var propertyInfo = typeof(ServiceRequest).GetProperty(p_Criteria);
var sortedList1 = new List<ServiceRequest>();
var sortedList2 = new List<ServiceRequest>();
var myServiceRequests = GetMyServiceRequests();
var otherServiceRequests = GetOthersServiceRequests();
if (p_sortDescending)
{
sortedList1 = myServiceRequests
.AsEnumerable()
.OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList();
sortedList2 = otherServiceRequests.AsEnumerable()
.OrderByDescending(x => propertyInfo.GetValue(x, null))
.ThenBy(x => x.Client.LastNameFirst).ToList();
}
else
{
sortedList1 = myServiceRequests.AsEnumerable()
.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();
sortedList2 = otherServiceRequests.AsEnumerable()
.OrderBy(x => propertyInfo.GetValue(x, null))
.ThenBy(x => x.Client.LastNameFirst).ToList();
}
var allSRs = p_ShowAll == false ? sortedList1.Concat(sortedList2).Take(1000)
.ToList() : sortedList1.Concat(sortedList2).ToList();
return allSRs;
}
But I can't seem to make this method work if the orderby column is in a child table (a table related to the parent though an FKey).
So the question is how do I make that work?
EF isn't really designed with dynamic sorting in mind. But there are alternatives you can use for cases like this without replacing the rest of your EF code.
For example, with Tortuga Chain you can write:
ds.From("ServiceRequests", [filter]).WithSorting (new SortExpression(p_Criteria, p_sortDescending)).ToCollection<ServiceRequest>().Execute();
You can also just generate SQL directly, but I don't recommend that approach because you have to carefully check the sort expression to ensure it is actually a column name and not a SQL injection attack.

How to match string in 2 diff collection and return the collection items that did not match in LINQ

I have a 2 collection of diff types. i want to match a string in those collection and return the collection which did not match.
1) ac_CategoryList
2) mw_CharityList
would like to match if ac_CategoryList.Title is there in mw_CharityList.EntryTitle. if it is not there, than return the ac_CategoryList collection items which are not matched. and return one more collection of mw_CharityList type which matched in ac_CategoryList.Title. because i need to update the status in mw_CharityList collection.
var var charityList = _db.mw_CompetitionsEntry.Where(e => e.IsInvalid == false && e.IsPublished).ToList(); // first get the entire valid collection
var categoryList = _db.ac_Category.Where(c => c.Title != null && c.IsDeleted == false).ToList(); // get the entire valid collection
var titleNotExitsCollection = categoryList.Where(c => charityList.Any(e => e.EntryTitle.Trim() != c.Title.Trim())).ToList();
var titleExitsCollection = charityList.Where(e => categoryList.Any(c => c.Title.Trim() == e.EntryTitle.Trim())).ToList();
right now titleNotExitsCollection and titleExitsCollection returns the same no of records. i dont know what i am doing wrong... please help
Looks like there is a not operator missing, try:
var titleNotExitsCollection = categoryList.Where(c => !charityList.Any(e => e.EntryTitle.Trim() == c.Title.Trim())).ToList();
var commonTitles = categoryList.Select(x=>x.Title.Trim())
.Intersect(charityList.Select(x=>x.EntryTitle.Trim()));
var titleNotExitsCollection = categoryList.Where(x=>!commonTitles.Contains(x.Title))
.ToList();
var titleExitsCollection = charityList.Where(x=>commonTitles.Contains(x.EntryTitle))
.ToList();

Categories

Resources