.net core 2.0 如何为两个具有详细信息部分的相关实体创建表单

.net core 2.0 how to create a form for two related entities with detail section

我是 .net core 的新手,我不知道如何为具有相关数据的两个实体创建表单并将数据保存到 dbcontext。 支持我有两个实体如下

public partial class invoice
{
    public int Id;
    public int invoiceNo;
    public string supplierName; 
    public ICollection<invoiceDetail> invoiceItems {get;set;}
}

public partial class invoiceDetail
{
    public int Id;
    public int InvoiceId;
    public string itemname;
    public int quantity;
}

我如何拥有一个视图页面,使我能够添加发票详细信息并在 InvoiceDetails Table 中包含项目数量? 提前致谢。

如果您想在添加发票详细信息时在 InvoiceDetails Table 中包含项目数,则需要在 invoice Table.

中添加 ItemCount 字段

下面是我做的代码中的主要代码片段,你可以参考

invoice Table 和 invoiceDetail Table

的变化
public  class invoice
{
    public int Id { get; set; }
    public int invoiceNo { get; set; }
    public string supplierName { get; set; }
    public int ItemCount { get; set; }
    public ICollection<invoiceDetail> invoiceItems { get; set; }
}
   public  class invoiceDetail
{
    public int Id { get; set; }
    public string itemname { get; set; }
    public int quantity { get; set; }
    public int InvoiceId { get; set; }
    public invoice Invoice { get; set; }
}
   protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<invoiceDetail>()
                    .Property<int>("InvoiceId");

        modelBuilder.Entity<invoiceDetail>()
                    .HasOne(id => id.Invoice)
                    .WithMany(i => i.invoiceItems)
                    .HasForeignKey("InvoiceId");
    }

查看页面,在添加发票时使用javascript添加多个发票明细

@model SaveMultipleRows.Models.invoice

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

<h2>Create</h2>
<hr/>
<div class="form-group">
    <label asp-for="invoiceNo" class="control-label"></label>
    <input asp-for="invoiceNo" class="form-control" id="invoiceNo"/>
</div>
<div class="form-group">
    <label asp-for="supplierName" class="control-label"></label>
    <input asp-for="supplierName" class="form-control" id="supplierName"/>
</div>

<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th style="width:150px">Item Name</th>
            <th style="width:150px">Quantity</th>
            <th></th>
        </tr>
    </thead>
    <tbody></tbody>
    <tfoot>
        <tr>
            <td><input type="text" id="txtItemName" /></td>
            <td><input type="text" id="txtQuantity" /></td>
            <td><input type="button" id="btnAdd" value="Add" /></td>
        </tr>
    </tfoot>
</table>

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

javascript,使用ajax到post数据给控制器

@section Scripts
{
<script type="text/javascript">
    $("#btnAdd").click(function () {
        var ItemName = $("#txtItemName");
        var Quantity = $("#txtQuantity");

        var tBody = $("#tblCustomers > TBODY")[0];
        var row = tBody.insertRow(0);

        //Add ItemName cell.
        var cell = $(row.insertCell(0));
        cell.html(ItemName.val());
        //Add Quantity cell.
        cell = $(row.insertCell(1));
        cell.html(Quantity.val());

        //Clear the Textboxes.
        ItemName.val("");
        Quantity.val("");
    });

    $("body").on("click", "#btnCreate", function () {

        //Loop through the Table rows and build a JSON array of invoiceItems.
        var invoiceItems = new Array();
        $("#tblCustomers TBODY TR").each(function () {
            var row = $(this);
            var invoiceItem = {};
            invoiceItem.ItemName = row.find("TD").eq(0).html();
            invoiceItem.Quantity = row.find("TD").eq(1).html();
            invoiceItems.push(invoiceItem);
        });

        //Populate invoice data
        var invoice = {};
        invoice.invoiceNo = $("#invoiceNo").val();
        invoice.supplierName = $("#supplierName").val();
        invoice.invoiceItems = invoiceItems;
        invoice.ItemCount = invoiceItems.length; //Count the number of invoiceItems 

        $.ajax({
            type: "POST",
            url: "/invoices/CreateInvoice",
            data: JSON.stringify(invoice),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r + " record(s) inserted.");
            }
        });
    });
</script>
}

控制器中的CreateInvoice方法

[HttpPost]
    public async Task<IActionResult> CreateInvoice([FromBody] invoice invoice)
   {
            _context.Add(invoice);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));

    }