What I have is a list of entities coming back from a database that I want to pivot so that I end up with a new list of entities with the duplicates removed and the pivoted items attached to the new entity.
Currently I have a simple solution like this:
IQueryable<Entity> results // being passed in from calling method.
List<Entity> pivotedEntities = new List<Entity>();
foreach (Entity entity in results)
{
if (pivotedEntities.Contains(entity))
{
Entity matchedEntity = pivotedEntities.Find(e => e.Id == entity.Id);
matchedEntity.RelatedEntities.Add(entity.RelatedEntity);
}
else
{
pivotedEntities.Add(new Entity());
}
}
return pivotedEntities.AsQueryable();
This works fine however I want to be able to achieve the same thing with a LINQ query on the IQueryable results variable so that it maintains its deffered execution rather than executing as soon as I enter the foreach.
I have other methods that get called around this code that also alter the IQueryable and I then want to execute the call to the database once all filters have been applied.
Hope that all makes sense.
Maybe this will reduce few loops.
List<Entity> pivotedEntities = new List<Entity>();
int index = 0;
foreach (Entity entity in results)
{
index = pivotedEntities.IndexOf(e => e.Id == entity.Id);
if (index>-1)
{
pivotedEntities[index].RelatedEntities.Add(entity.RelatedEntity);
}
else
{
pivotedEntities.Add(new Entity());
}
}
return pivotedEntities.AsQueryable();
Related
Here im getting Multipul values as 1,2,3 for ENQUIRY_CODE
public void HRUpdateStatus(string ENQUIRY_CODE, int uid)
{
var x = (from e in db.EMS_ENQUIRYREGISTRATION_MASTER
where e.ENQUIRY_CODE == ENQUIRY_CODE
select e).ToList();
foreach (var abc in x)
{
abc.HRowner = uid;
db.SaveChanges();
}
...
}
Please help me where im doing mistake
A LINQ statement will never change the source sequence.
LINQ is not meant to do that.
The proper solution depends on which kind of DbContext you are using. If you use entity framework you'll have to fetch the items before you can update one or more of the properties.
In your case, you want to change one property of all fetched values to the same new value. Consider creating an extension function for your DbContext. See extenstion methods demystified
The following takes an IQueryable sequence of some source class (TSource), and an action that should be performed on each source element.
public void ForEach<TSource>(this IQueryable<TSource> source,
Action<TSource> action)
{
var fetchedItems = source.ToList();
foreach (var fetchedItem in fetchedItems)
{
action(fetchedItem);
}
}
Usage:
using (var dbContext = new MyDbContext())
{
db.EMS_ENQUIRYREGISTRATION_MASTER
.Where (registrationMaster => registrationMaster.ENQUIRY_CODE == ENQUIRY_CODE)
.ForEach(registrationMaster => registrationMaster.HRowner = uid);
db.SaveChanges();
}
I chose to return void instead of IEnumerable<TSource> to indicate to users of the function that the queried data is materialized and might have been changed. After all the following might have been confusing:
IQueryable<Student> students = ...
var updatedStudents = students.ForEach(student => student.Grades.Add(new Grade(...))
.Take(2)
.ToList();
You want to communicate that all students are updated, not just the 2. Consider returning an IReadonlyList<TSource> or similar, so you don't have to materialize the data again.
I think this is what you mean:
var codes = ENQUIRY_CODE.Split(',').ToList();
var x= db.EMS_ENQUIRYREGISTRATION_MASTER.Where(s => codes.Contains(s.ENQUIRY_CODE)).ToList();
I am new to LINQ,
I want to generate a list of objects from my dbcontext where a certain field is set to true.
This is what I have so far, but I am getting an error about a select?
using (var db = new dbContext())
{
return (from s in db.sims.Where(x=>x.has_been_modified == true) select x).ToList();
}
EDIT:
//Returns a list of entries which where marked as edited in the sim managment database
private List<String> GetUpdatedEntries()
{
using (var db = new dbContext())
{
return db.sims.Where(x => x.has_been_modified).ToList();
}
}
select s, not x and this will work. (because you do from s)
shorter way
return db.sims.Where(x => x.has_been_modified).ToList();
For your Edit
the method return type should be a List<Sim>, not a List<String>
This will work
return db.sims.Where(x=>x.has_been_modified).ToList();
method Linq looks cleaner here
you don't need to check your bool against true
in your previous answer you used s as context and selected x, changing to select s should work also
Consider using lazy loading and don't add ToList at the end of every query
Why does this code not work? It inserts an object but does not delete it
public int Toggle(RequestArchive RequestArchiveObj)
{
var ra = DataContext.RequestArchives.Where(rec => rec.UserId == RequestArchiveObj.UserId && rec.RequestId == RequestArchiveObj.RequestId);
if(ra.Count() > 0)
{
foreach (var item in ra)
{
DataContext.DeleteObject(item);
}
}
else
{
DataContext.AddToRequestArchives(RequestArchiveObj);
}
DataContext.SaveChanges();
return RequestArchiveObj.Id;
}
There's a potentially dangerous issue with your code and your problem might relate to that:
If you loop through your query object (the object returned by DataContext.RequestArchives.Where()) without executing it, you're going to have a roundtrip to the database for every single item in the loop. This is called the N+1 selects problem.
You can mitigate this using the ToList() method:
var ra = DataContext.RequestArchives
.Where(rec =>
rec.UserId == RequestArchiveObj.UserId &&
rec.RequestId == RequestArchiveObj.RequestId)
.ToList(); // this executes the query
// ...
foreach (var item in ra) // without ToList() this will query every item by itself
{
DataContext.DeleteObject(item); // and this might collide with the query
}
I'm not sure about this, but maybe the deletion problem occurs because you try to delete objects while still querying them through the foreach loop. If that is the case, it should work once you're using ToList() as recommended above.
I have a gridview, the datasource of which is the following function:
public static List<Train> GetTrainsByIDs(int [] ids) {
using (var context = new MyEntities())
{
return ids.Select(x => context.Trains.Single(y => y.TrainID ==x)).AsQueryable().Include(x=>x.Station).ToList();
}
}
The grid view has an ItemTemplate of <%# Eval("Station.Name") %>.
This causes the error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection despite the fact that I used the include method.
When I change the function to
public static List<Train> GetTrainsByIDs(int [] ids) {
using (var context = new MyEntities())
{
return context.Trains.Where(x => ids.Contains(x.TrainID)).Include(x=>x.Station).ToList();
}
}
it works fine, but then they come out in the wrong order, and also if I have 2 ids the same I would like 2 identical trains in the list.
Is there anything I can do other than create a new viewmodel? Thank you for any help
As for the first query: that's deferred execution.You created an IEnumerable of Trains, noticed that it did not have the Include method, so cast it to IQueryable, added the Include and added the ToList() to prevent lazy loading.
But As per MSDN on DbExtensions.Include:
This extension method calls the Include(String) method of the IQueryable source object, if such a method exists. If the source IQueryable does not have a matching method, then this method does nothing.
(emphasis mine)
The result of the select is an IEnumerable converted to IQueryable, but now implemented by EnumerableQuery which does not implement Include. And nothing happens.
Now the data enters the grid which tries to display the station, which triggers lazy loading while the context is gone.
Apart from that, this design has another flaw: it fires a query for each id separately.
So the second query is much better. It is one query, including the Stations. But now the order is dictated by the order the database pleases to return. You could use Concat to solve this:
IQueryable<Train> qbase = context.Trains.Include(x=>x.Station);
IQueryable<Train> q = null;
foreach (var id in ids)
{
var id1 = id; // Prevent modified closure.
if (q == null)
q = qbase.Where(t => t.Id == id1);
else
q = q.Concat(qbase.Where (t => t.Id == id1));
}
The generated query is not very elegant (to say the least) but after all it is one query as opposed to many.
After reading #Gert Arnold's answer, and getting the idea of doing it in 2 stages, I managed very simply using the first query like this:
using (context = new MyEntities())
{
var trns = context.Trains.Include(x => x.Station);
return ids.Select(x => trns.Single(y => y.TrainID == x)).ToList();
}
I have a method that updates a ReportRecipient object in EF. The primitives work fine; the headache comes in when trying to manage a M2M relationship with the RecipientGroups objects.
Please take a look at this code:
public IReportRecipient ModifyRecipientWithGroupAssignments(IEnumerable<Guid> groupIds, IReportRecipient recipient)
{
var entity = Context.ReportRecipients
.Include("RecipientGroups")
.FirstOrDefault(e => e.ReportRecipientId == recipient.ReportRecipientId)
.FromIReportRecipient(recipient);
var toRemove = entity.RecipientGroups
.Where(e => !groupIds.Contains(e.GroupId))
.ToList();
//remove group assignments that no longer apply
foreach (var group in toRemove)
{
if (group != null)
{
entity.RecipientGroups.Attach(group);
entity.RecipientGroups.Remove(group);
}
}
var toAdd = entity.RecipientGroups
.Where(e => groupIds.Contains(e.GroupId))
.ToList();
//add new groups that weren't there before
foreach (var group in toAdd)
{
if (group != null)
{
entity.RecipientGroups.Attach(group);
}
}
return entity;
}
... my problem is on the var ToAdd... line. Even if I have a collection of Guids in groupIds that match Guids representing RecipientGroup objects in the database, toAdd always evaluates to an empty collection. I would think the Contains() function would work for this scenario; can someone please explain if I am doing something wrong?
You should load the RecipientGroups you want to add from the database (Context.RecipientGroups I guess), not from the collection you want to add them to (entity.RecipientGroups in the code sample).