2

I have two tables A and B. Their relation is 1:N. I want to update one field in ALL the children tables, but I'm don't know what LINQ expression to use to do that -- shouldn't be too difficult.

I was thinking something like:

parentEntity.childrens.All(..lambda expr..).field = value;

But obviously it's not working.

I know the other option is a foreach(..), but I'd prefer L2E if possible.

Majid
  • 13,853
  • 15
  • 77
  • 113
D.Rosado
  • 5,634
  • 3
  • 36
  • 56
  • http://weblogs.asp.net/pwelter34/archive/2011/11/29/entity-framework-batch-update-and-future-queries.aspx – Mohsen Apr 09 '13 at 06:44

2 Answers2

8

You can't set a property on all items of a collection without somehow looping through that collection, either with foreach, for, List<T>.ForEach, or similar.

If you want to keep it in one line, you could do something like:

author.Books.ToList().ForEach(b => b.PublishYear = 1999);
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • I agree. Linq is fundamentally a QUERY language; it is meant to query a collection without changing it. I would make the query and then foreach over the items you've queried as a separate statement. – Kaido Aug 12 '11 at 16:03
  • I was traying not to move the entire collection to memory, but you both are right. Cheers – D.Rosado Aug 12 '11 at 16:06
3

You'd have to either loop through and update all or use a raw SQL statement executed through Entity Framework which would be much more efficient for this kind of thing.

Chris Snowden
  • 4,982
  • 1
  • 25
  • 34
  • 1
    As this answer indicates: http://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework/3642383#3642383 – Kit Aug 12 '11 at 15:59