-1
我正在使用实体框架核心来构建一个简单的Web应用程序。对于这个应用程序,我创建了一个名为Company的模型,其中包含基本业务信息+联系人列表(销售代表)。允许用户编辑MVC中的列表项目?
这里是我的模型:
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);
}
这是不正确的,因为代码只允许我编辑公司信息。如何修改代码,以便我可以在同一个编辑视图上编辑公司&的联系人?
工作所以我不能评论,但不幸的是,但我可以建议使用视图模型,而不是实际的Dto,然后将视图模型从POST映射到Dto - 或使用AutoMapper来处理这些映射。然后,您只需在映射和保存后使用'_context.Companies.Update(companyToUpdate);'。 – ColinM