我有一个很长的模型类,有很多属性和导航字段。
public class Customers
{
public Customers()
{
this.Files = new HashSet<Files>();
}
public int CustomerID { get; set; }
public int InspectionID { get; set; }
public int Position { get; set; }
public Nullable<int> Height { get; set; }
public Nullable<int> Weight{ get; set; }
//.....many more properties
//there are some navigation properties below
//.....
}
为了分解视图(并且业务逻辑需要它),我创建了大约 14 个具有此类属性子集的局部视图,并且相应的局部视图在页面加载时加载到主编辑视图中。(更新后评论)在另一个视图上,当单击链接时,将调用编辑 GET 操作,并将 CustomerID 参数传递给控制器,该控制器加载带有相应部分视图的编辑视图,如下所示
@model myApplication.Models.CustomersViewModel //Trial 2 from below uses //this and
@model myApplication.Models.Customers //Trial 1 from below uses this
@{
ViewBag.Title = "Edit";
}
@section Styles {
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div>
@*All commong properties here*@
</div>
@*the corresponding PartialView with subset /selected/ properties here -UPDATE: please note that the partailview is named as the PK i.e. inspection id (Sorry, I worte wrongly on the initial post)
@Html.Partial("_edittemplates/" + Model.InspectionID)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>
现在,我不想使用这些属性的子集为 14 个局部视图中的每一个创建 14 个 ViewModel,因为这看起来很浪费。我想做的是使用一个大的 ViewModel 并使用 automapper 管理视图上加载的属性(主要和部分)并映射这些特定属性,而无需复制(复制粘贴)模型类的所有属性进入客户视图模型。
试验一:
我试图将类映射到自身,但由于弄乱了外键值/数据库关系而适得其反 - 错误消息类似于“无法更改关系,因为一个或多个外键属性不可为空.. ……”。然后我添加了 .ForAllMembers(opt=>opt.Ignore()) ,它变得更加混乱。
Customers customers= db.Customers .SingleOrDefault(c => c.CustomerID == id);
Customers editcustomers = AutoMapperMappings.mapper.Map<Customers , Customers >(customers);
试验 2:所以,我认为另一种无需创建 14 个局部视图且无需使用 automapper 复制粘贴所有属性的方式就是这样
public class CustomersViewModel
{
public Customers customers { get; set; }
}
然后映射和反向映射
cfg.CreateMap<CustomersViewModel, Customers>().ReverseMap();
GET 控制器
Customers customers = db.Customers.SingleOrDefault(c => c.CustomerID == id);
CustomerEditViewModel editcustomers = AutoMapperMappings.mapper.Map<Customers, CustomersEditViewModel>(customers);
editcustomers.customers = customers;
return View(editcustomers);
然后是 POST 方法
Customers locate = db.Customers .Find(editcustomers.customers.customersID);
AutoMapperMappings.mapper.Map(editcustomers.customers, locate);
//locate = editcomponents.components;
//db.Entry(locate).State = EntityState.Modified;
db.SaveChanges();
但是,即使映射顺利进行并且没有错误并且 GET 加载了视图并且 POST 收到了修改后的值,db.SaveChanges(); 没有收到修改后的值更新不会发生。
但是,如果从 Model 类中复制所有属性并将它们复制到 ViewModel 中,则通过 automapper 的映射将起作用,并且视图上的数据将被保存
public class CustomersViewModel
{
public int CustomerID { get; set; }
public int InspectionID { get; set; }
public int Position { get; set; }
public Nullable<int> Height { get; set; }
public Nullable<int> Weight{ get; set; }
//...and all other properties
}
我的问题是,有没有办法用一个大的 ViewModel 做到这一点,而无需再次重新列出模型类的所有属性?非常感谢您的建议!