Still working on my first UWP / MVVM / EF kernel.
I do not want my viewmodels to have any knowledge of DbContext. So I created the following ItemService class introduced in my view models.
public class ItemService : IItemService { public async Task SaveAsync(Item item) { using (var db = new MyDbContext()) { db.Items.Add(item); await db.SaveChangesAsync(); } } }
My ItemViewModel contains the following command:
public RelayCommand SaveCommand { get; private set; } private async void Save() { if (!SaveCommand.CanExecute(Item)) return; await ItemService.SavAsync(Item); }
This works great when I save an item. The SaveAsync method creates a new instance of DbContext, adds the just created item, and then commits the changes to the database.
My question is about updating an existing record. I was talking about something like this:
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();
I just don't like this solution! I need to copy all the properties of an element into dbItem. What if I forget him? I could implement ICloneable, but I find it real overhead to do this for ALL of my entities.
So what is the correct template here. Best way to update a record driven by a view model?
Thanks a lot in advance, Julien
source share