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();
}
}
利点は、すべてのロジックがクリーンで構造化されているため、単体テストとコードのメンテナンスが簡単になることです。