通过实体框架更新

本文关键字:更新 框架 实体 | 更新日期: 2023-09-27 18:00:26

帮帮我解决这个问题,我真的很困惑!

我只是想更新一些东西!这是我的控制器(后操作(:

[HttpPost]
public ActionResult Edit(CategoryViewModel categoryViewModel)
{
            if(ModelState.IsValid)
            {
                _categoryService.UpdateCategory(categoryViewModel.Id);
            }
            return View();
}

这是我的服务类(我的问题是关于这个类的,我不知道如何更新它(

public CategoryViewModel UpdateCategory(Guid categoryId)
{
            var category = _unitOfWork.CategoryRepository.FindBy(categoryId);
            var categoryViewModel = category.ConvertToCategoryViewModel();
             _unitOfWork.CategoryRepository.Update(category);
            _unitOfWork.SaveChanges();
            return categoryViewModel;
}

最后我的基本存储库是这样的:

private readonly DbSet<T> _entitySet;
public void Update(T entity)
{
            _entitySet.Attach(entity);
}

UnitOfWork也是这样的:

public class UnitOfWork : IUnitOfWork
{
    private IRepository<Category> _categoryRepository;
    public IRepository<Category> CategoryRepository
    {
            get { return _categoryRepository ?? (_categoryRepository = new Repository<Category>(_statosContext)); }
    }
}

通过实体框架更新

更改UpdateCategory以接受CategoryViewModel而不仅仅是Guid。将实例UpdateFromViewModel(CategoryViewModel model)方法添加到 Category 对象,该对象的工作是从模型中获取属性并将其传输到 EF 实体。之后,其余代码应该可以工作了。还有其他模式也可以用来完成这一点,但考虑到你现有的模式,这应该让你越过终点线。

public class Category
{
    public void LoadFromModel(CategoryViewModel model)
    {
        // Transfer properties from model to entity here
    }
}
public class CategoryService
{
    public void UpdateCategory(CategoryViewModel model)
    {
        var category = _unitOfWork.CategoryRepository.FindBy(model.CategoryId);
        category.LoadFromModel(model);
        _unitOfWork.SaveChanges();
        model.CategoryId = category.CategoryId;
    }
}