[英]Update list using Entity Framework Core
I have two classes, Student
and Details
.我有两个班级, Student
和Details
。
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
}
I display the list of all students on the web page and I would like to allow the editing of student details for the selected student.我在 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>
The page model is as below, 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");
}
}
When a student is selected, I then display the details in a HTML table and would like EF Core to keep track of changes in the HTML table.选择学生后,我会在 HTML 表中显示详细信息,并希望 EF Core 跟踪 HTML 表中的更改。 To achieve this, I create an IList
of Details
and display it, but when the user updates any values, I get an error that the IList
doesn't exist in the model which I can understand because the model only has DB table column info and not the IList
of rows as such.为此,我创建了一个Details
列表并显示它,但是当用户更新任何值时,我收到一个错误,即IList
IList
我可以理解,因为 model 只有 DB 表列信息和不是IList
这样的行。
Would anyone be able to suggest how can I achieve this?谁能建议我如何实现这一目标?
I got it working after changing the type as below, from IList
to List
在将类型从IList
更改为List
后,我得到了它的工作
[BindProperty]
public List<TestEFCore.Models.Details> Details { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.