繁体   English   中英

创建新连接项时如何更新相关表?

[英]How to update a related table when a new connection item is created?

我在 SQL 服务器中有 3 个表

笔记本电脑表:笔记本电脑ID(int),笔记本电脑名称(nvarchar),笔记本电脑可用(位)

PersonTable : PersonID(int), PersonName(nvarchar)

ConnectionTable : ConnectionID(int)、LaptopLaptopID(int)、PersonPersonID(int)

在 ASP.NET EF Core (web) 中,我为所有三个表创建了一个 CRUD。 创建新连接项时,如何在 LaptopTable 中将 LaptopAvailable 位设置为 false?

这是我的 ConnectionsController.cs 中的“创建”部分:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ConnectionID,LaptopLaptopID,PersonPersonID")] Connection connection)
{
if (ModelState.IsValid)
{
_context.Add(connection);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["LaptopLaptopID"] = new SelectList(_context.Laptops, "LaptopID", "LaptopName", connection.LaptopLaptopID);
ViewData["PersonPersonID"] = new SelectList(_context.Persons, "PersonID", "PersonName", connection.PersonPersonID);
return View(connection);
}

您需要从连接的 LaptopId 获取现有的笔记本电脑记录并进行更新。

// Add connection
_context.Add(connection);

// Find & update flag for that laptop
var existingLaptop = _context.FirstOrDefault(x => x.LaptopId == connection.LaptopLaptopID)
if(existingLaptop)
    existingLaptop.LaptopAvailable = false;

// Save both changes
await _context.SaveChangesAsync();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM