What is the correct way of updating a record from the view model?
<p>Still working on my first UWP/MVVM/EF Core application.</p>

<p>I don't want my viewmodels to have any knowledge of the DbContext. So I created the following ItemService class, injected into my view models.</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemService : IItemService
{
    public async Task SaveAsync(Item item)
    {
        using (var db = new MyDbContext())
        {
            db.Items.Add(item);
            await db.SaveChangesAsync();
        }
    }
}
</code></pre>

<p>My ItemViewModel contains the following command :</p>

<pre class="lang-cs prettyprint-override"><code>public RelayCommand SaveCommand { get; private set; }

private async void Save()
{
    if (!SaveCommand.CanExecute(Item))
        return;

    await ItemService.SavAsync(Item);
}
</code></pre>

<p>This works great when I save an item. The SaveAsync method creates a new instance of the DbContext, adds the just created item and then commits the changes to the database.</p>

<p>My question is about the updating of an existing record. I thoug about something like this :</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemService : IItemService
{
    public async Task UpdateAsync(Item item)
    {
        using (var db = new MyDbContext())
        {
            Item dbItem = (from i in db.Items
                           where i.Id = item.Id
                           select i).FirstOrDefault();

            // Here I should duplicate all the item's properties into dbItem ones

            await db.SaveChangesAsync();
        }
    }
}
</code></pre>

<p>I just don't like this solution !
I have to copy all the properties of item into dbItem. What if I forgot one ? I could implement ICloneable but I find it a real overhead to do that for ALL my entities.</p>

<p>So what is the correct pattern here. The best way to update a record managed by a view model ?</p>

<p>Many thanks in advance,
Julien</p>