我是新來的Asp.net MVC,可以真正使用視圖模型如何工作的一些澄清。查看模型如何鏈接到數據庫?
從我的理解,視圖模型只用於暴露從域模型到視圖的必要字段。我發現很難理解的是域模型通過Dbset鏈接到Db。因此,當我使用域模型將數據發佈到控制器時,這些數據可以在Db中找到路徑,這對我來說很有意義。
從我看過的View模型的示例中,它們沒有被Dbset引用。那麼如何將數據發佈到View模型中找到進入數據庫的路徑。 EF是否將視圖模型中的字段與域模型中匹配的字段進行匹配?
感謝您的幫助
我是新來的Asp.net MVC,可以真正使用視圖模型如何工作的一些澄清。查看模型如何鏈接到數據庫?
從我的理解,視圖模型只用於暴露從域模型到視圖的必要字段。我發現很難理解的是域模型通過Dbset鏈接到Db。因此,當我使用域模型將數據發佈到控制器時,這些數據可以在Db中找到路徑,這對我來說很有意義。
從我看過的View模型的示例中,它們沒有被Dbset引用。那麼如何將數據發佈到View模型中找到進入數據庫的路徑。 EF是否將視圖模型中的字段與域模型中匹配的字段進行匹配?
感謝您的幫助
正如Jonathan所言,AutoMapper將幫助您將ViewModel實體映射到您的Domain模型。這裏有一個例子:
您認爲您的視圖模型(CreateGroupVM)工作:
@model X.X.Areas.Group.Models.CreateGroupVM
@using (Html.BeginForm(null,null, FormMethod.Post, new { @class="form-horizontal", role="form"}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.LabelFor(model => model.Title, new { @class = "col-lg-4 control-label" })
@Html.TextBoxFor(model => model.Title, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Title)
@Html.LabelFor(model => model.Description, new { @class = "col-lg-4 control-label" })
@Html.TextBoxFor(model => model.Description, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Description)
@Html.LabelFor(model => model.CategoryId, new { @class = "col-lg-4 control-label" })
@Html.DropDownListFor(x => x.CategoryId, Model.Categories)
@Html.ValidationMessageFor(model => model.CategoryId)
<div class="form-group">
<div class="col-lg-offset-4 col-lg-8">
<button type="submit" class="btn-u btn-u-blue">Create</button>
</div>
</div>
}
視圖模型(CreateGroupVM.cs): 注意我們是如何通過在類別列表 - 你如果您嚴格使用域模型,則無法執行此操作,因爲您無法在組模型中傳遞類別列表。這在我們的視圖中給了我們強類型的助手,並且沒有ViewBag的用法。
public class CreateGroupVM
{
[Required]
public string Title { get; set; }
public string Description { get; set; }
[DisplayName("Category")]
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
域模型(Group.cs):
public class Group
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public int CreatorUserId { get; set; }
public bool Deleted { get; set; }
}
在你HttpPost創建動作 - 你讓AutoMapper進行映射,然後保存到數據庫中。請注意,默認情況下,AutoMapper將映射同名的字段。您可以閱讀https://github.com/AutoMapper/AutoMapper/wiki/Getting-started以開始使用AutoMapper。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateGroupVM vm)
{
if (ModelState.IsValid)
{
var group = new InterestGroup();
Mapper.Map(vm, group); // Let AutoMapper do the work
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}
視圖模型不會綁定到您的數據庫。您需要創建一個新的域模型,並使用來自視圖模型的數據填充它,以便將其保存到數據庫中。當然,必須這樣做是非常煩人的,並且有人創建了AutoMapper來處理這個問題。
使用automapper,您可以將視圖模型中的屬性與域模型中的屬性進行匹配,然後根據需要將它們添加到數據庫中。
感謝您的詳細描述。清理了我的困惑。 – ricky89