Model 和 ViewModel 之间的交互应该如何?
视图模型向视图描述数据。它用于表示逻辑并向视图提供数据。这些模型用于描述来自数据源(如 sql 或文件)的数据。
您的视图模型中的内容示例:
public class CustomerViewModel
{
public long Id { get; set; }
public bool IsFoundingMember { get { return Id < 1000; } }
public string Name { get; set; }
public bool IsABaggins { get { return !string.IsNullOrWhiteSpace(Name) ? Name.EndsWith("Baggins") : false; } }
}
模型中的东西示例
public class Customer
{
public long? Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public DateTime? DateOfBirth { get; set; }
}
我会尝试将逻辑分组为可维护性的函数。
说:
ActionResult Save(CustomerModel cm)
{
if(!ValidateCustomerModel(cm))
{
//Deal with invalid data
}
UpdateCustomer(cm);
//continue
}
public bool ValidateCustomerModel(CustomerModel model)
{
//Do stuff
return true;
}
public void UpdateCustomer(CustomerModel model)
{
Customer c = new Customer();
c.Id = cm.Id;
c.Email = cm.Email;
context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
在分离出所有 CRUD 逻辑之后,您可以为该逻辑创建一些类,并查看 Unity、Ninject 或普通的旧构造函数注入。
例如构造函数注入
public class MyController : Controller
{
private readonly ICustomerDL _customerDL;
public MyController(ICustomerDL customerDL)
{
_customerDL = customerDL;
}
//Load your implementation into the controller through the constructor
public MyController() : this(new CustomerDL()) {}
ActionResult Save(CustomerModel cm)
{
if(!ValidateCustomerModel(cm))
{
//Deal with invalid data
}
_customerDL.UpdateCustomer(cm);
//continue
}
public bool ValidateCustomerModel(CustomerModel model)
{
//Do stuff
return true;
}
}
public interface ICustomerDL
{
void UpdateCustomer(CustomerModel model);
}
public class CustomerDL : ICustomerDL
{
public void UpdateCustomer(CustomerModel model)
{
Customer c = new Customer();
c.Id = cm.Id;
c.Email = cm.Email;
context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
}
好处是您的所有逻辑都将是干净和结构化的,这将使单元测试和代码维护变得轻而易举。