Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific fields to update in EF

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?

like image 558
work question Avatar asked Feb 06 '17 10:02

work question


People also ask

How do I update my EF model from database?

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.

How do you update the status of an object in EF?

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.

What does update() do in Entity Framework?

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.

How to specify fields that should not be updated?

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:


1 Answers

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.

like image 101
Anestis Kivranoglou Avatar answered Oct 27 '22 16:10

Anestis Kivranoglou