0

How to update a property in Entityframework core

var mydata= _dbContext.MyTable.Where(a => a.Status== "CA")

This gives m more than one record and i want to update only one property in these records . Forexample i want to set IsAvailable = false for all the records here in mydata.

Can i do this without a for loop...

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
coder11 b
  • 99
  • 5

1 Answers1

-1

I don't know if I understood your question right but maybe this solves your issue:

try using the Update() method.

Example:

_dbContext.MyTable
    .Where(a => a.Status == "CA")
    .Update(a => new MyTable { IsAvailable = false });

here it sets the isAvailable = false to every entry that matches the "Where()" query

Dru.Dru
  • 59
  • 7
  • The `.Update(a => new MyTable { ... })` syntax is from Entity Framework Plus, a separate library which you do not mention. – CodeCaster Apr 05 '23 at 11:47
  • is it possible without a separate library. I have used ExecuteUpdateAsync method of ef7.0 but since i am unable to mock it i had to change my implementation like above – coder11 b Apr 05 '23 at 12:24
  • so you want to update one property of each entry you getting back of that were() method? – Dru.Dru Apr 05 '23 at 12:29
  • @coder11b, do not mock DbContext and it's methods. Use SqlLite-in-Memory and use in tests real DbContext. – Svyatoslav Danyliv Apr 05 '23 at 12:29
  • @coder11b if this is the case then maybe try: mydata.ToList().ForEach(e => e.IsAvailable = false); – Dru.Dru Apr 05 '23 at 12:41
  • @SvyatoslavDanyliv can you suggest some example – coder11 b Apr 05 '23 at 13:03
  • A lot of them in internet [unit-testing-with-inmemory-provider-and-sqlite-in-memory-database-in-ef-core](http://www.mukeshkumar.net/articles/efcore/unit-testing-with-inmemory-provider-and-sqlite-in-memory-database-in-ef-core) – Svyatoslav Danyliv Apr 05 '23 at 13:07