Here is another issue I have faced in ASP.NET Core Let say I have 2 Tables:
Accommodation
( ID, Name, LocationID)
Location
(ID, Address, Latitude, Longitude)
And I have a form:
Name:
Address:
Latitude:
Longitude:
Then when a button is clicked I want the value to be updated on both table and also MAP the LocationID to Accommodation table How should I code it in EF Core? Like a proper way
You could try the following example I made :
Accommodation Model and Location Model
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
}
DbSet two model in DbContext
public class MVCDbContext:DbContext
{
public MVCDbContext(DbContextOptions<MVCDbContext> options) : base(options)
{ }
public DbSet<Accommodations> Accommodations { get; set; }
public DbSet<Location> Location { get; set; }
}
The design of the view ,pay attention to the asp-for
of the input tag
@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>
The action to update both table
[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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.