如何更新多个表中的多行

时间:2019-02-05 14:25:29

标签: asp.net-mvc

我希望能够通过一次提交来更新日期或编辑多个表中的多行。

我正在创建一个规范系统,其中一部分将创建物料清单(BOM)。我已经为BOM表的规格创建了一个标题表,并为组成BOM表的组件创建了一个线表。为简单起见,假设我的标题表包含以下字段。

RovingHeader表:

RovingNo

说明

ModDate

RovingLine表:

RovingNo

ItemNo

数量

RowId

标题行中有一行,而行表中有多行。

编辑视图如下:

enter image description here 1.5

我可以更新“描述”和“最后修改日期”,它是RovingHeader表的一部分。下面的下两行来自RovingLines表。我只能更新第一个项目和数量,而不能更新第二个。当我将“ CH700”更改为“ CH900”并提交时,更改永远不会提交。我该如何解决这个问题。

我知道我需要创建某种列表或供声明,但是我不确定该如何处理。

谢谢您的帮助

下面是我的代码:

型号:

sing System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Spec5.Models
{
    public partial class RovingHeader
    {
        [Key]
        [Display(Name = "Roving Number")]
        [StringLength(20)]
        [Required]
        public string RovingNo { get; set; }
        [StringLength(60)]
        [Required]
        public string Description { get; set; }
        [Display(Name = "Last Modified Date")]
        [DataType(DataType.Date)]
        public DateTime? ModDate { get; set; }

        public ICollection<RovingLine> RovingLine { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Spec5.Models
{
    public partial class RovingLine
    {

        [Display(Name = "Roving Number")]
        public string RovingNo { get; set; }
        [Display(Name = "Part Number")]
        public string ItemNo { get; set; }
        [Column(TypeName = "decimal(18, 5)")]
        public decimal? Qty { get; set; }
        [Key]
        public int RowId { get; set; }

        [ForeignKey("RovingNo")]
        public RovingHeader RovingHeader { get; set; }
    }
}

上下文:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Spec5.Models
{
    public partial class SPECContext : DbContext
    {
        public SPECContext()
        {
        }

        public SPECContext(DbContextOptions<SPECContext> options)
            : base(options)
        {
        }

        public DbSet<RovingHeader> RovingHeader { get; set; }
        public DbSet<RovingLine> RovingLine { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("ProductVersion", "2.2.1-servicing-10028");

            modelBuilder.Entity<RovingHeader>(entity =>
            {
                entity.HasKey(e => e.RovingNo);

                entity.ToTable("Roving_Header");

                entity.HasIndex(e => e.RovingNo)
                    .HasName("IX_Roving_Header");

                entity.Property(e => e.RovingNo)
                    .HasColumnName("Roving_No")
                    .HasMaxLength(20)
                    .ValueGeneratedNever();

                entity.Property(e => e.Description).HasMaxLength(50);

                entity.Property(e => e.ModDate)
                    .HasColumnName("Mod_Date")
                    .HasColumnType("date");
            });

            modelBuilder.Entity<RovingLine>(entity =>
            {
                entity.HasKey(e => e.RowId);

                entity.ToTable("Roving_Line");

                entity.HasIndex(e => e.RovingNo)
                    .HasName("IX_Roving_Line");

                entity.Property(e => e.ItemNo)
                    .HasColumnName("Item_No")
                    .HasMaxLength(20);

                entity.Property(e => e.Qty)
                    .HasColumnName("QTY")
                    .HasColumnType("numeric(18, 5)");

                entity.Property(e => e.RovingNo)
                    .HasColumnName("Roving_No")
                    .HasMaxLength(20);
            });
        }
    }
}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Spec5.Models;

namespace Spec5.Controllers
{
    public class RovingHeadersController : Controller
    {
        private readonly SPECContext _context;

        public RovingHeadersController(SPECContext context)
        {
            _context = context;
        }
        // GET: RovingHeaders/Details/5
        public async Task<IActionResult> Details(string id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var rovingHeader = await _context.RovingHeader
                 .Include(s => s.RovingLine)
                .FirstOrDefaultAsync(m => m.RovingNo == id);
            if (rovingHeader == null)
            {
                return NotFound();
            }

            return View(rovingHeader);
        }

        // GET: RovingHeaders/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: RovingHeaders/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("RovingNo,Description,ModDate")] RovingHeader rovingHeader)
        {
            if (ModelState.IsValid)
            {
                _context.Add(rovingHeader);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(rovingHeader);
        }

        // GET: RovingHeaders/Edit/5
        public async Task<IActionResult> Edit(string id, List<RovingLine> rovingLines)
        {
            if (id == null)
            {
                return NotFound();
            }

            var rovingHeader = await _context.RovingHeader
                .Include(s => s.RovingLine)
                .FirstOrDefaultAsync(m => m.RovingNo == id);


            if (rovingHeader == null)
            {
                return NotFound();
            }
            return View(rovingHeader);
        }

        // POST: RovingHeaders/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(List<RovingLine> rovingLines, string id, [Bind("RovingNo,Description,ModDate")] RovingHeader rovingHeader, [Bind("RovingNo,ItemNo,Qty,RowId")] RovingLine rovingLine)
        {
            if (id != rovingHeader.RovingNo)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(rovingHeader);
                    _context.Update(rovingLine);
                   await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RovingHeaderExists(rovingHeader.RovingNo))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(rovingHeader);
        }

        // GET: RovingHeaders/Delete/5
        public async Task<IActionResult> Delete(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var rovingHeader = await _context.RovingHeader
                .FirstOrDefaultAsync(m => m.RovingNo == id);
            if (rovingHeader == null)
            {
                return NotFound();
            }

            return View(rovingHeader);
        }

        // POST: RovingHeaders/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            var rovingHeader = await _context.RovingHeader.FindAsync(id);
            _context.RovingHeader.Remove(rovingHeader);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool RovingHeaderExists(string id)
        {
            return _context.RovingHeader.Any(e => e.RovingNo == id);
        }

        public async Task<IActionResult> Index(string searchString)
        {
            var rovingHeader = from m in _context.RovingHeader
                         select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                rovingHeader = rovingHeader.Where(s => s.RovingNo.Contains(searchString));
            }

            return View(await rovingHeader.ToListAsync());

        }
        [HttpPost]

        public string Index(string searchString, bool notUsed)

        {

            return "From [HttpPost]Index: filter on " + searchString;

        }
    }
}

查看

@model Spec5.Models.RovingHeader
@{
    ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4></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="RovingNo" />
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ModDate" class="control-label"></label>
                <input asp-for="ModDate" class="form-control" />
                <span asp-validation-for="ModDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                    <table class="table">
                        <tr>
                            <th></th>
                            <th>Item</th>
                            <th>QTY</th>
                        </tr>
                        <tr>                            
                                @foreach (var item in Model.RovingLine)
                                {
                                 <tr>
                                 <td>
                                     <input type="hidden" name="RovingNo" value="@item.RovingNo" />
                                 </td>
                                 <td>
                                    <input type="text" name="ItemNo" value="@item.ItemNo" />
                                 </td>
                                 <td>
                                    <input type="text" name="Qty" value="@item.Qty" />
                                 </td>
                                 <td>
                                    <input type="hidden" name="RowId" value="@item.RowId" />
                                 </td>
                                 </tr>
                                }                            
                       </tr>
                    </table>           
            </div>
                <div class="form-group">
                    <input type="submit" value="Save" class="btn btn-primary" />                    
                </div>
        </form>
    </div>
</div>

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

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

1 个答案:

答案 0 :(得分:0)

您似乎正在做很多事情,例如类中的键注释和上下文类中的流利Api配置。

与此控制器操作类似

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(List<RovingLine> rovingLines, string id, [Bind("RovingNo,Description,ModDate")] RovingHeader rovingHeader, [Bind("RovingNo,ItemNo,Qty,RowId")] RovingLine rovingLine)
    {
        if (id != rovingHeader.RovingNo)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(rovingHeader);
                _context.Update(rovingLine);
               await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RovingHeaderExists(rovingHeader.RovingNo))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(rovingHeader);
    }

您具有RovingLine的列表参数和对象参数,并且仅绑定了对象参数。 我不确定,但这似乎不是更新列表的首选方法。

也许这不是唯一的错误,这是我认识到的第一件事。