gpt4 book ai didi

c# - 从 View 模型更新记录的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 22:00:10 24 4
gpt4 key购买 nike

<分区>

仍在开发我的第一个 UWP/MVVM/EF Core 应用程序。

我不希望我的 View 模型对 DbContext 有任何了解。因此,我创建了以下 ItemService 类,并将其注入(inject)到我的 View 模型中。

public class ItemService : IItemService
{
public async Task SaveAsync(Item item)
{
using (var db = new MyDbContext())
{
db.Items.Add(item);
await db.SaveChangesAsync();
}
}
}

我的 ItemViewModel 包含以下命令:

public RelayCommand SaveCommand { get; private set; }

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

await ItemService.SavAsync(Item);
}

这在我保存项目时效果很好。 SaveAsync 方法创建 DbContext 的新实例,添加刚刚创建的项目,然后将更改提交到数据库。

我的问题是关于现有记录的更新。我想像这样的事情:

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();
}
}
}

我只是不喜欢这个解决方案!我必须将项目的所有属性复制到 dbItem 中。如果我忘了一个怎么办?我可以实现 ICloneable,但我发现为我的所有实体执行此操作确实是一项开销。

那么这里正确的模式是什么。更新由 View 模型管理的记录的最佳方式?

非常感谢,朱利安

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com