I want to get all records from a database with @where, then update them. To do this, I have created a query like this:
public async Task MarkAllAsActive()
{
var currentUserId = _userManager.GetCurrentUserId();
await _workOrders.Where(row => row.Status == WorkOrderStatus.Draft).ForEachAsync(row =>
{
row.Status = WorkOrderStatus.Active;
_uow.MarkAsChanged(row, currentUserId);
});
}
But this query selects all fields from the database which isn't good. To solve this I try to select just specific fields like ID
, Status
:
public async Task MarkAllAsActive()
{
var currentUserId = _userManager.GetCurrentUserId();
await _workOrders.Select(row=>new WorkOrder { Id=row.Id,Status=row.Status}).Where(row => row.Status == WorkOrderStatus.Draft).ForEachAsync(row =>
{
row.Status = WorkOrderStatus.Active;
_uow.MarkAsChanged(row, currentUserId);
});
}
But it return this error:
The entity or complex type 'DataLayer.Context.WorkOrder' cannot be constructed in a LINQ to Entities query.
I've seen a similar post and the same error, but my problem is different because I want to update.
How can I do this?
How do I update EF model from database first? Right-click the design area and select Update Model in the database. Select the refresh tab of the Updater wizard, then select Tables > DBA > Students. Click Finish. After the update has been completed, the database map shows the new firstname property.
Update mechanism (currently introduced to EF Core). Db context is utilised. Appear methods and then “walk the objects graph” to explicitly specify the status of a specific property on that graph. DBContext offers Update and ChangeRange methods for interacting with individual entities.
This tells Entity Framework update the entire object in the database. Perfect for 99% of the time when doing an update statement but not for a delete statement.
The other way to specify fields that should not be updated. In case you use a view model, you can use new operator to create your data model and copy the fields you want to update:
Sadly you have to fetch the entire entity. In order to update an entity with EF, the class type edited has to be a DbContext mapped entity .
If you want to Update without fetching Entities to the server , and without writing any SQL you can use Entity Framework Extended Library .
See the update section on the site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With