我为自定义视图模板创建了一个viewmodel类。现在我在Controller类中调用数据库保存方法。现在我想把这个逻辑移到Repository类。如何在我的存储库类中访问我的viewModel特性?我很感激任何意见。谢谢。
这是我的代码。
视图模型
public SelectList StatusList { get; set; }
[Required(ErrorMessage = "* Required")]
public string Status { get; set; }
[Required]
public DateTime? StartDate { get; set; }
我的控制器类:
[HttpPost]
public ActionResult Create(CreateViewModel viewModel)
{
if (ModelState.IsValid)
{
// go and save your view model data
using (var adapter = new DataAccessAdapter())
{
TestEntity test1 = new TestEntity();
test1.statusId = Convert.ToInt32(viewModel.Status);
adapter.SaveEntity(test1);
TestEntity1 test2 = new TestEntity2();
test2.mId = test1.mId;
test2.startDate = viewModel.startDate;
adapter.SaveEntity(test2);
}
}
}
答案 0 :(得分:3)
您不希望访问存储库中的视图模型属性,您希望将视图模型属性映射回实体类并将实体传递到存储库。该实体应该位于MVC应用程序和数据库都知道的库中。
public class TestController
{
public ITestRepository _repository;
public TestController(ITestRepository repository)
{
_repository = repository;
}
public ActionResult Create(CreateViewModel viewModel)
{
var entity = new TestEntity()
{ statusId = Int32.Parse(viewModel.Status) };
var entity2 = new TestEntity2()
{ mId = entity.mId,
startDate = viewModel.startDate };
_repository.SaveEntity(entity);
_repository.SaveEntity2(entity2);
}
}