繁体   English   中英

使用 Entity Framework Core 更新列表

[英]Update list using Entity Framework Core

我有两个班级, StudentDetails

public class Student
{
    [Key]
    public int StudentD { get; set; } // PK
    public string StudentName { get; set; }
    public string StudentType { get; set; }
    public virtual ICollection<Details> Details { get; set; } // FK
}
public class Details
{
    [Key]
    public int DetailsID { get; set; } // PK
    public string Property { get; set; }
    public string Value { get; set; }
    public virtual Student Student { get; set; }
    public int StudentID { get; set; } // FK
}

我在 web 页面上显示所有学生的列表,我想允许编辑所选学生的学生详细信息。

<form method="post">
<table class="table">
    <thead>
        <tr>
            <th></th>
            <th> @Html.DisplayNameFor(model => model.Details[0].Name) </th>
            <th> @Html.DisplayNameFor(model => model.Details[0].Value) </th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model.Details)
    {
        <tr>
        <td> <input type="hidden" asp-for=@item.DetailsID /> </td>
        <td> @Html.DisplayFor(modelItem => item.Property) </td>
        <td contenteditable='true'> @Html.DisplayFor(modelItem => item.Value) </td>
        </tr>
    }
    </tbody>
</table>
<div class="form-group">
    <input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>

model页面如下,

public class EditModel : PageModel
{
    private readonly TestEFCore.Data.TestEFCoreContext _context;
    public EditModel(TestEFCore.Data.TestEFCoreContext context)
    {
        _context = context;
    }

    [BindProperty]
    public IList<TestEFCore.Models.Details> Details { get; set; }

    public async Task<IActionResult> OnGetAsync(int? id)
    {
        if (id == null) { return NotFound(); }
        Detailss = await _context.Details.Where(m => m.StudentID == id).ToListAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid) { return Page(); }

        _context.Attach(Details).State = EntityState.Modified;

        try { await _context.SaveChangesAsync(); }
        catch (DbUpdateConcurrencyException) { throw; }

        return RedirectToPage("./Index");
    }
}

选择学生后,我会在 HTML 表中显示详细信息,并希望 EF Core 跟踪 HTML 表中的更改。 为此,我创建了一个Details列表并显示它,但是当用户更新任何值时,我收到一个错误,即IList IList我可以理解,因为 model 只有 DB 表列信息和不是IList这样的行。

谁能建议我如何实现这一目标?

在将类型从IList更改为List后,我得到了它的工作

[BindProperty]
public List<TestEFCore.Models.Details> Details { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM