【发布时间】:2017-09-24 11:08:27
【问题描述】:
我正在使用 Entity Framework Core 构建一个简单的 Web 应用程序。对于这个应用程序,我创建了一个名为 Company 的模型,其中包括基本业务信息 + 联系人列表(销售代表)。
这是我的模型:
public class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; }
public virtual List<Contact> Contacts { get; set; }
}
public class Contact
{
[Key]
public int ContactID { get; set; }
[ForeignKey("Company")]
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
这是控制器的 index() 方法:
// GET: Companies
public async Task<IActionResult> Index()
{
List<Company> viewModelData = await _context.Companies
.Include(c => c.Contacts)
.ToListAsync();
return View(viewModelData);
}
编辑方法:
// GET: Companies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var company = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (company == null)
{
return NotFound();
}
return View(company);
}
// POST: Companies/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] Company company)
{
if (id == null)
{
return NotFound();
}
var companyToUpdate = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (await TryUpdateModelAsync<Company>(
companyToUpdate,
"",
i => i.Name, i => i.Promo, i => i.Contacts
)) {
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction("Index");
}
return View(companyToUpdate);
}
这是不正确的,因为代码只允许我编辑公司信息。如何修改代码以便我可以在同一个编辑视图中同时编辑公司及其联系人?
【问题讨论】:
-
我从来没有真正使用过
TryUpdateModel,所以很遗憾我不能对此发表评论,但是我可以建议使用视图模型而不是实际的 Dto,然后从 POST 映射视图模型到 Dto - 或使用 AutoMapper 来处理这些映射。然后你只需要在映射后使用_context.Companies.Update(companyToUpdate);,然后保存。
标签: asp.net asp.net-mvc visual-studio entity-framework