问题描述
请原谅我是 C# 和 Razor Pages 的新手。我有一个基于父记录 (AccountYears) 的页面和一个儿童表 (AccountYearsMonths)。如果我更改 AccountYearsMonths 中的状态字段并保存记录,则子项不会更新。当我在 OnPostAsync 过程中进入调试器时,它显示没有与父级关联的子级。但是, OnGetAsync 使所有子项都可以显示和编辑。这是我的方法代码:
namespace Seasons.Areas.Setup.Pages.FinanceAccountYears
{
public class EditModel : PageModel
{
private readonly MyApplication.Data.ApplicationDbContext _context;
public EditModel(MyApplication.Data.ApplicationDbContext context)
{
_context = context;
}
[BindProperty]
public AccountYears AccountYears { get; set; }
public async Task<IActionResult> OnGetAsync(Guid? id)
{
if (id == null)
{
return NotFound();
}
AccountYears = await _context.AccountYears
.Include(ay => ay.AccountYearsMonths)
.AsTracking()
.FirstOrDefaultAsync(ay => ay.AccountYearsID == id);
if (AccountYears == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(AccountYears).State = EntityState.Modified
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AccountYearsExists(AccountYears.AccountYearsID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
private bool AccountYearsExists(Guid id)
{
return _context.AccountYears.Any(e => e.AccountYearsID == id);
}
}
}
我的模型如下:
public class AccountYears //Parent Table
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid AccountYearsID { get; set; }
[Display(Name = "Accounts Year Name"),Required]
public string AccountYearsName { get; set; }
//AccountYearsMonths
public ICollection<AccountYearsMonths> AccountYearsMonths { get; set; }
}
public class AccountYearsMonths // Child Table
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid AccountYearsMonthsID { get; set; }
[Required]
public Guid AccountYearsID { get; set; }
public AccountYears AccountYears { get; set; }
[Display(Name = "Month Name"),Required]
public string AccountYearsMonthsName { get; set; }
}
请谁能给我一个线索,为什么 AccountYears 在 OnGetAsync 上填充 AccountYearsMonths,但在运行 OnPostAsync 时丢失了对 AccountYearsMonths 的引用(在调试器中显示为 null)?非常感谢提前
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)