Foreach delete with linq - linq

The following statement should delete someCars from allCars, and it works, however I was wondering if there is a better solution which specifically uses only linq
foreach (var car in someCars)
{
db.allCars.DeleteObject(car);
}
Note that db is the instance of the db entities.
Any help would be much appreciated.

You can use EntityFramework.Extended library to delete entities based on some condition (library available from Nuget):
db.allCars.Delete(car => /*condition*/);

using Linq as ForEach:
db.allCars.Where(/* condition */).ToList().ForEach(car => db.allCars.Remove(car));
in the same line of this answer :) , How do I delete multiple rows in Entity Framework (without foreach)

You can use:
db.allCars.RemoveAll(db.allCars.Where(/* condition */));

Related

Linq-to-Entities query result that used params from multiple tables/Dbs

Greetings Everyone
I am using EF6 and VS13 Free Community.
I followed a database First Approach.
I currently have a project (.net mvc) that contains multiple databases and tables
i am using the Entities & Linq queries and i couldn't figure out how to use the result of the queries i create when it's inside an if statement i saw solution but it only works when i use a single table not multiple ones. Example :
var query = from varA in db1.table_name
from varB in db2.table_name
where
varA.X = varB.X
select new
{
varA.stuff,
varB.something
}
Resolved didn't search deep enough
a foreach did it for me
foreach (var result in query)
{
...
}

How can I use set operations to delete objects in an entitycollection that match a collection of view models?

Here is a very basic example of what I want to do. The code I have come up with seems quite verbose... ie looping through the collection, etc.
I am using a Telerik MVC grid that posts back a collection of deleted, inserted and updated ViewModels. The view models are similar but not exactly the same as the entity.
For example... I have:
Order.Lines. Lines is an entity collection (navigation property) containing OrderDetail records. In the update action of my controller using the I have a List names DeletedLines pulled from the POST data. I also have queried the database and have the Order entity including the Lines collection.
Now I basically want to tell it to delete all the OrderDetails in the Lines EntityCollection.
The way I have done it is something like:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.Where(l => l.Key == line.Key).SingleOrDefault())
}
I was hoping there was a way that I could use .Interset() to get a collection of entities to delete and pass that to DeleteObject.. however, DeleteObject seems to only accept a single entity rather than a collection.
Perhaps the above is good enough.. but it seemed like there should be an easier method.
Thanks,
BOb
Are the items in DeletedLines attached to the context? If so, what about this?
foreach (var line in DeletedLines) db.DeleteObject(line);
Response to comment #1
Ok, I see now. You can make your code a bit shorter, but not much:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.SingleOrDefault(l => l.Key == line.Key))
}
I'm not sure if DeleteObject will throw an exception when you pass it null. If it does, you may be even better off using Single, as long as you're sure the item is in there:
foreach (var line in DeletedLines) {
db.DeleteObject(Order.Lines.Single(l => l.Key == line.Key))
}
If you don't want to re-query the database and either already have the mapping table PK values (or can include them in the client call), you could use one of Alex James's tips for deleting without first retrieving:
http://blogs.msdn.com/b/alexj/archive/2009/03/27/tip-9-deleting-an-object-without-retrieving-it.aspx

NHibernate delete from LINQ results

I'm wondering about the best usage of the delete method in nhibernate.
If you go the entity than just call delete and send it, but if not you need to query it or write a query and send it to delete method.
I'm wondering if its possible to write a linq expression and send it to delete.
Is it possible to perform a Linq transformation to hql and than call session.Delete(query)
with the generated hql?
I want to call Session.Delete, and give it a linq so it can know what to delete without selecting the data. Do you know a class that can convert linq expression to hql?
You now can directly in linq with NHibernate 5.0
//
// Summary:
// Delete all entities selected by the specified query. The delete operation is
// performed in the database without reading the entities out of it.
//
// Parameters:
// source:
// The query matching the entities to delete.
//
// Type parameters:
// TSource:
// The type of the elements of source.
//
// Returns:
// The number of deleted entities.
public static int Delete<TSource>(this IQueryable<TSource> source);
Exemple:
var tooOldDate = System.DateTime.Now.AddYears(5);
session.Query<User>()
.Where(u => u.LastConnection <= tooOldDate)
.Delete();
The Q in LINQ stands for "Query". So, no, you can't use a LINQ expression for delete.
That said, NH's query language, HQL, does support that.
In the same way that you can say "from Foo where Bar = :something" to get all the foos matching a condition, you can do this:
session.CreateQuery("delete Foo where Bar = :something")
.SetParameter("something", ...)
.ExecuteUpdate();
I have submitted a pull request for NH-3659 - Strongly Typed Delete. The link is available at nhibernate.jira.com/browse/NH-3659.
I know this is an old question but for those reading this now. NHibernate 5 released Oct 10, 2017 has added a Delete Linq extension
from documentation 17.6.3. Deleting entities
Delete method extension expects a queryable defining the entities to delete. It immediately deletes them.
session.Query<Cat>()
.Where(c => c.BodyWeight > 20)
.Delete();
I'm sure it would be possible to do what you want but the bottom line is that it doesn't make a lot of sense (not sure why you want to give NHibernate the select criteria when you can do it in a single statement, your approach would end up causing 2 hits to the database), having said that, one easy option you could do, is query the IDs using LINQ and pass those to NHibernate
int[] deleteIds = (from c in Customer where {some condition} select c.Id).ToArray<int>();
session.CreateQuery("delete Customer c where c.id in (:deleteIds)")
.SetParameterList("deleteIds", deleteIds)
.ExecuteUpdate();

LINQ Query to find all tags?

I have an application that manages documents called Notes. Like a blog, Notes can be searched for matches against one or more Tags, which are contained in a Note.Tags collection property. A Tag has Name and ID properties, and matches are made against the ID. A user can specify multiple tags to match against, in which case a Note must contain all Tags specified to match.
I have a very complex LINQ query to perform a Note search, with extension methods and looping. Quite frankly, it has a real code smell to it. I want to rewrite the query with something much simpler. I know that if I made the Tag a simple string, I could use something like this:
var matchingNotes = from n in myNotes
where n.Tags.All(tag => searchTags.Contains(tag))
Can I do something that simple if my model uses a Tag object with an ID? What would the query look like. Could it be written in fluent syntax? what would that look like?
I believe you can find notes that have the relevant tags in a single LINQ expression:
IQueryable<Note> query = ... // top part of query
query = query.Where(note => searchTags.All(st =>
note.Tags.Any(notetag => notetag.Id == st.Id)));
Unfortunately there is no “fluent syntax” equivalent for All and Any, so the best you can do there is
query = from note in query
where searchTags.All(st =>
note.Tags.Any(notetag => notetag.Id == st.Id))
select note;
which is not that much better either.
For starters see my comment; I suspect the query is wrong anyway! I would simplifiy it, by simply enforcing separately that each tag exists:
IQueryable<Note> query = ... // top part of query
foreach(var tagId in searchTagIds) {
var tmpId = tagId; // modified closures...
query = query.Where(note => note.Tags.Any(t => t.Id == tmpId));
}
This should have the net effect of enforcing all the tags specified are present and accounted for.
Timwi's solution works in most dialects of LINQ, but not in Linq to Entities. I did find a single-statement LINQ query that works, courtesy of ReSharper. Basically, I wrote a foreach block to do the search, and ReSharper offered to convert the block to a LINQ statement--I had no idea it could do this.
I let ReSharper perform the conversion, and here is what it gave me:
return searchTags.Aggregate<Tag, IQueryable<Note>>(DataStore.ObjectContext.Notes, (current, tag) => current.Where(n => n.Tags.Any(t => t.Id == tag.Id)).OrderBy(n => n.Title));
I read my Notes collection from a database, using Entity Framework 4. DataStore is the custom class I use to manage my EF4 connection; it holds the EF4 ObjectContext as a property.

Linq for NHibernate and fetch mode of eager loading

Is there a way to set the fetchmode to eager for more than one object using linq for nhibernate. There seems to be an expand method which only allows me to set one object. However I need to set it for more than one object. Is this possible? Thanks
The new Linq provider does it a little differently:
var customers = session.Query<Customer>().Fetch(c => c.Orders).ToList();
More here:
http://mikehadlow.blogspot.com/2010/08/nhibernate-linq-eager-fetching.html
just use it more then once.
IList<Entity> GetDataFromDatabase()
{
var query = session.Linq<Entity>();
query.Expand("Property1");
query.Expand("Property2");
return query.ToList();
}
As far as I can see, this is not equivalent: SetFetchMode hydrates an objects tree and the Expand method retrieves a cartesian product.
In contiune to #Mike Hadlow answer, fetching next level (grandchildren) you need to do:
var customers = session.Query<Customer>()
.FetchMany(c => c.Orders)
.ThenFetchMany(o => o.OrderLines).ToList();

Resources