这是我在ASP.NET Core中面临的另一个问题 假设我有2张桌子:
Accommodation
( ID, Name, LocationID)
Location
(ID, Address, Latitude, Longitude)
我有一个表格:
Name:
Address:
Latitude:
Longitude:
然后,当单击按钮时,我要在两个表上同时更新值,还要将LocationID映射到Accommodation表 我应该如何在EF Core中进行编码?像正确的方式
答案 0 :(得分:0)
您可以尝试以下示例:
住宿模型和位置模型
public class Accommodations
{
public int ID { get; set; }
public string Name { get; set; }
public int LocationID { get; set; }
[ForeignKey("LocationID")]
public Location Location { get; set; }
}
public class Location
{
public int ID { get; set; }
public string Address { get; set; }
//other stuff you want
}
Db在DbContext中设置两个模型
public class MVCDbContext:DbContext
{
public MVCDbContext(DbContextOptions<MVCDbContext> options) : base(options)
{ }
public DbSet<Accommodations> Accommodations { get; set; }
public DbSet<Location> Location { get; set; }
}
视图的设计,请注意输入标签的asp-for
@model MVC2_1Test.Models.Accommodation.Accommodations
@{
ViewData["Title"] = "Accommondation";
}
<h2>Accommondation</h2>
<div class="row">
<div class="col-md-4">
<form id="form" class=".has-error" asp-action="CreateAccommodation">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group ">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="cusName" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Location.Address" class="control-label"></label>
<input asp-for="Location.Address" class="form-control" id="age" />
<span asp-validation-for="Location.Address" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
更新两个表的操作
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateAccommodation([FromForm]Accommodations accommodation)
{
if (ModelState.IsValid)
{
_context.Add(accommodation);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(accommodation);
}