How to add values to 2 table then map foreign key from one table to another table in Entity Framework Core using Postgresql? c# entity-framework-core postgresql


Here is another issue I have faced in ASP.NET Core Let say I have 2 Tables:

( ID, Name, LocationID)
(ID, Address, Latitude, Longitude)

And I have a form:


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

3/1/2019 6:59:21 AM

Popular Answer

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; }
    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";


<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 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 class="form-group">
            <input type="submit" value="Create" class="btn btn-default" />


The action to update both table

    public async Task<IActionResult> CreateAccommodation([FromForm]Accommodations accommodation)
        if (ModelState.IsValid)
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        return View(accommodation);
3/1/2019 6:57:29 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow