私は、 「product」という名前MedicalProductController
の(モデルクラス)をに変換しようとしています。これにより、(viewModelクラス)が返されます。MedicalProduct
IEnumerable<MedicalProduct>
GetMedicalProductViewModelList
IEnumerable<MedicalProductViewModel>
SQL 呼び出しを最小限に抑えようとしています。他のstackoverflowメンバーのアドバイスに従って。
IEnumerable<MedicalProduct>
しかし、「製品」は私のMedicalProductController
クラスに変わりません
MedicalProductController
public class MedicalProductController : Controller
{
private MvcMedicalStoreDb _db = new MvcMedicalStoreDb();
// other CRUD code omitted for brevity.
// =============
// Edit HttpGet
// =============
public ActionResult Edit(int id = 0)
{
MedicalProduct product = _db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
var productList = product as IEnumerable<MedicalProduct>;
var viewModelList = GetMedicalProductViewModelList(productList);
return View(viewModelList);
}
// =============
// Edit HttpPost
// =============
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MedicalProduct product)
{
if (ModelState.IsValid)
{
_db.Entry(product).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
var productList = product as IEnumerable<MedicalProduct>;
var viewModel = GetMedicalProductViewModelList(productList);
return View(viewModel);
}
// =====================
// Mapper Class Helper
// =====================
public IEnumerable<MedicalProductViewModel> GetMedicalProductViewModelList(IEnumerable<MedicalProduct> productList)
{
var brandList = _db.Brands.ToArray();
var mapper = new MedicalProductMapper();
return mapper.MapMedicalProductViewModel(productList, brandList);
}
参考までに、マッピング クラスを次に示します。
MedicalProductMapper
public class MedicalProductMapper
{
// =====================
// Model to ViewModel
// =====================
public IEnumerable<MedicalProductViewModel> MapMedicalProductViewModel(IEnumerable<MedicalProduct> medicalProductList, IEnumerable<Brand> brandList)
{
var brandSelectListItem = brandList.Select(b => new SelectListItem()
{
Text = b.Name,
Value = b.Name
});
var viewModelList = medicalProductList.Select(p => new MedicalProductViewModel()
{
BrandID = p.BrandID,
BrandName = brandList.SingleOrDefault(b => b.ID == p.BrandID).Name,
BrandSelectListItem = brandSelectListItem,
ID = p.ID,
Price = p.Price,
Name = p.Name
});
return viewModelList;
}
// =====================
// ViewModel to Model
// =====================
public MedicalProduct MapMedicalProduct(MedicalProductViewModel VM)
{
var model = new MedicalProduct()
{
Name = VM.Name,
Price = VM.Price,
BrandID = VM.BrandID
};
return model;
}
}