Reputation: 91
Using EF Core Console App I need to give an admin user the ability to select a checkbox, and on button press, basically run this pseudocode statment
update EF Table set active = 'Yes' where userID = userID of checkbox
I have no problem running Select
with EF but how to do an update?
EDIT
I currently have this syntax
foreach ((int Id, DateTime? submissionDate, string status) tuple in apiData)
{
if (ctx.Test.Any(x => x.OrderId == tuple.Id))
{
Test ts = new Test();
ts.Status = tuple.status;
ctx.Test.Add(ts);
ctx.SaveChanges();
}
else
{
Test ts = new Test();
ts.OrderId = tuple.Id;
ts.PdfDownloaded = tuple.submissionDate;
ts.Status = tuple.status;
ctx.Test.Add(ts);
ctx.SaveChanges();
}
}
but when i run the code, I get this error on an update (the if).
System.InvalidOperationException: 'The instance of entity type 'Test' cannot be tracked because another instance with the same key value for {'OrderId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
EDIT 2
I have also tried this approach
var records = ctx.Test.Where(x => x.OrderId == tuple.Id);
records.ForEach(x => x.Status = tuple.status);
ctx.SaveChanges();
but I get this compile error on the foreach
'IQueryable' does not contain a definition for 'ForEach' and no accessible extension method 'ForEach' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)
Upvotes: 0
Views: 196
Reputation: 617
var entity = context.table.WHERE(userId == checkBox).FirstOrDefault();
entity.property = "value"
context.saveChanges();
Upvotes: 0
Reputation: 135
You should first get the record(s) that you want to update
var records = context.EFTable.Where(x => x.userID == UserId).ToList();
Then you should set active to yes, on all those objects
records.ForEach(x => x.active = "yes");
Finally, save all the changes
context.saveChanges();
Upvotes: 1