簡體   English   中英

更新 EF 核心中一對多關系的數據

[英]updating data on one to many relation in EF core

我正在嘗試更新一個表(FlightClasses),其中包含與表(Flight)具有一對多關系的多行,但我無法使用更改后的值更新它任何人都可以幫助我嗎

航班的 Model class 我想更新與此表中的行鏈接的其他航班等級表上的行

namespace Airline.Models
{
    public class FlightModel
    {
        public int Id { get; set; }
        public string FlightName { get; set; }
        public string FlightNo { get; set; }
        public string OriginCity { get; set; }
        public string DestinationCity { get; set; }
        public DateTime Departure { get; set; }
        public DateTime Arrival { get; set; }
        public virtual ICollection<FlightClassesModel> FlightClasses { get; set; }
    }
}

FlightClasses Model class

namespace Airline.Models
{
    public class FlightClassesModel
    {

        public int FlightClassesModelId { get; set; }
        public type Class { get; set; }
        public int AvailableSeats { get; set; }
        public double Price { get; set; }
        public virtual FlightModel Flight { get; set; }

        public int? FlightId { get; set; }
    }
    public enum type
    {
        Business_Class,
        First_Class,
        Club_Class
    }
}

看法

@model Airline.Models.FlightModel

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<h4>FlightModel</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="FlightName" class="control-label"></label>
                <input asp-for="FlightName" class="form-control" />
                <span asp-validation-for="FlightName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FlightNo" class="control-label"></label>
                <input asp-for="FlightNo" class="form-control" />
                <span asp-validation-for="FlightNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="OriginCity" class="control-label"></label>
                <input asp-for="OriginCity" class="form-control" />
                <span asp-validation-for="OriginCity" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DestinationCity" class="control-label"></label>
                <input asp-for="DestinationCity" class="form-control" />
                <span asp-validation-for="DestinationCity" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Departure" class="control-label"></label>
                <input asp-for="Departure" class="form-control" />
                <span asp-validation-for="Departure" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Arrival" class="control-label"></label>
                <input asp-for="Arrival" class="form-control" />
                <span asp-validation-for="Arrival" class="text-danger"></span>
            </div>
            @foreach (var flightClass in Model.FlightClasses)
            {
                <div class="form-group">
                    <label asp-for="@flightClass.Class" class="control-label"></label>
                    <select class="form-control" asp-for="@flightClass.Class"  asp-items="Html.GetEnumSelectList<type>()"></select>
                    <span asp-validation-for="@flightClass.Class" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="@flightClass.AvailableSeats" class="control-label"></label>
                    <input asp-for="@flightClass.AvailableSeats" class="form-control" />
                    <span asp-validation-for="@flightClass.AvailableSeats" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="@flightClass.Price" class="control-label"></label>
                    <input asp-for="@flightClass.Price" class="form-control" />
                    <span asp-validation-for="@flightClass.Price" class="text-danger"></span>
                </div>
            }

            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

controller

public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var flightModel = await _context.Flight.FindAsync(id);
            if (flightModel == null)
            {
                return NotFound();
            }
            return View(flightModel);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, FlightModel flightModel)
        {
            if (id != flightModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(flightModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FlightModelExists(flightModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(flightModel);
        }

此代碼_context.Update(flightModel); 只會更新飛行模型,所以如果你想更新飛行類,你也必須從飛行模型中獲取飛行類,然后使用_context.Update(flightClasse); 對於 FlightClasses 中的所有實例。 最后你使用await _context.SaveChangesAsync();

使用 EntityFramework Core 更新父子(一對多關系)表中的數據

我們首先使用 FirstOrDefaultAsync 從數據庫中檢索 FlightModel 實體

   var entity = await _context.FlightModel
                .Include(s => s.FlightClassesModel)
                .FirstOrDefaultAsync(s => s.FlightModelId == id); 

在 Entry 方法的 CurrentValues 上使用 SetValues 來更新 FlightModel 的屬性

 _context.Entry(entity).CurrentValues.SetValues(FlightModel);

循環遍歷 FlightClassesModel 集合以根據需要更新或添加新的子實體。

foreach (var child in FlightModel.FlightClassesModel)
            {
                var childEntity = entity.FlightClassesModel.FirstOrDefault(c => c.FlightClassesModelId == child.FlightClassesModelId);
                if (childEntity != null)
                {
                    _context.Entry(childEntity).CurrentValues.SetValues(child);
                }
                else
                {
                    entity.FlightClassesModel.Add(child);
                }
            }

SaveChangesAsync 將更改保存到數據庫。

 await _context.SaveChangesAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM