如何使用Postgresql将值添加到2个表,然后将外键从一个表映射到Entity Framework Core中的另一个表?

时间:2019-02-28 01:47:56

标签: c# postgresql asp.net-core entity-framework-core

这是我在ASP.NET Core中面临的另一个问题 假设我有2张桌子:

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

我有一个表格:

Name:
Address:
Latitude:
Longitude:

然后,当单击按钮时,我要在两个表上同时更新值,还要将LocationID映射到Accommodation表 我应该如何在EF Core中进行编码?像正确的方式

1 个答案:

答案 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);
    }