0

これについて私を助けてください、私は本当に混乱しています!

何か更新したい!これは私のコントローラーです(ポストアクション):

[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)); }
    }
}
4

1 に答える 1

0

の代わりにUpdateCategoryを受け入れるように変更します。モデルからプロパティを取得して EF エンティティに転送するジョブを持つオブジェクトにインスタンス メソッドを追加します。その後、残りのコードは機能するはずです。これを達成するために使用できる他のパターンもありますが、既存のパターンを考えると、これでフィニッシュ ラインを越えられるはずです。CategoryViewModelGuidUpdateFromViewModel(CategoryViewModel model)Category

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;
    }
}
于 2013-02-20T16:38:10.627 に答える