1

According to this article https://visualstudiomagazine.com/articles/2019/07/01/updating-linq.aspx , I want to update collection set one field to NULL for all items

//Set all Entity_For = null 
   var relatedPlanToDos = DB.PlanToDos.Where(x => x.EntityFor != null && x.EntityFor.ID == entity.ID);
   relatedPlanToDos.Select(c => { c.EntityFor = null ; return c; }).ToList();

This is the syntax Error I get :

A lambda expression with a statement body can not be converted to an expression tree

Any help would be appreciated

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Sara N
  • 1,079
  • 5
  • 17
  • 45

2 Answers2

0

You should get all value from linq-to-sql first by .ToList()

var relatedPlanToDos = DB.PlanToDos.Where(x => x.EntityFor != null 
                                             && x.EntityFor.ID == entity.ID).ToList();

Then you can do this

relatedPlanToDos.Select(c => { c.EntityFor = null ; return c; }).ToList();

or

relatedPlanToDos.ForEach(c => c.EntityFor = null);

Tips

  1. You should know What is the difference between IQueryable<T> and IEnumerable<T>?

  2. Actually, you no need to check x.EntityFor != null, read the following the have a better understanding

How to check if the value exist in the database table ignoring null in LINQ C#

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

Change it to this:

var relatedPlanToDos = DB.PlanToDos.Where(x => x.EntityFor != null && x.EntityFor.ID == entity.ID).ToList().ForEach(c => c.EntityFor = null);
javachipper
  • 519
  • 4
  • 15