What is the correct way to update a record from a view model?

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(); // Here I should duplicate all the item properties into dbItem ones await db.SaveChangesAsync(); } } } 

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

+6
source share
1 answer

You must use the repository template in your application. Then you can completely separate your DAL layer from ViewmModels.On at the service level, where you can use AutoMapper to map the ViewModel to Entity and verse versa. At this point, you can do this at your service level. But you have to introduce a separate layer for the repository template (i.e. DAL) using dependency injection. Then you do not need to worry about mixing virtual machines and objects. In other words, they are on two separate layers if you implement the above template.

Therefore, you are using the EF core, you can use Autofac as an API DI.

What is AutoMapper?

AutoMapper is a simple small library created for a deceptive complex problem - getting rid of code that maps one object to another. This type of code is pretty boring and boring to write, so why not come up with a tool for this?

Here is the link: AutoMaster

Good article: General repository and work unit template, Entity Framework, Autofac

As suggested by @Sean Stayn , where you can use Prism . also.

Prism is the foundation for creating loosely coupled, supported, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms.

0
source

All Articles