简体   繁体   English

.net Core 2.2 EF:SaveChangesAsync() 将不相关的列设置为空

[英].net Core 2.2 EF: SaveChangesAsync() setting unrelated columns to null

I have an Asp.Net Core 2.2 application.我有一个 Asp.Net Core 2.2 应用程序。 I've written a couple of new Razor pages to update some new data to an existing model.我编写了几个新的 Razor 页面来将一些新数据更新到现有模型。

The problem is that when I "submit" my form and call SaveChangesAsync(), it updates the fields I've changed ... and it ERASES most of the other fields in the record.问题是,当我“提交”我的表单并调用 SaveChangesAsync() 时,它会更新我已更改的字段......并且它会擦除记录中的大多数其他字段。

The model has 40 or 50 properties;模型有 40 或 50 个属性; I'm only trying to update 3 or 4 of them.我只是想更新其中的 3 或 4 个。

But EVERYTHING except "ID" and the fields in my form are getting set to "null" by the update.但是,除了“ID”,并在我的表单中的字段一切由更新设置成“空”。

Q: Any idea what I'm missing?问:知道我错过了什么吗?

public class EditPageModel : PageModel
{
    private readonly Project.Models.MyContext _context;

    [BindProperty]
    public MyModel MyRecord { get; set; }

    public EditPageModel(Project.Models.MyContext context)
    {
        _context = context;
        // <= This is OK...

    public async Task<IActionResult> OnGetAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        MyRecord = await _context.MyModel.FirstOrDefaultAsync(m => m.ID == id);
        // <= This is OK, too: I call "return Page()" and everything looks fine...

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

        // Update DB
        _context.Attach(MyRecord).State = EntityState.Modified;
        try
        {
            await _context.SaveChangesAsync();  
        }
        catch (DbUpdateConcurrencyException)
        {
            // No exceptions, no errors or warnings: Never get here...
            ...
        }
        return RedirectToPage("./Index");

You have two options:您有两个选择:

Option 1: add hidden fields for each and every property in your model that don't need to be changed.选项 1:为模型中不需要更改的每个属性添加隐藏字段。

Option 2: load record from database, map properties from model to the db object and save changes, without attaching the binding model to the context.选项 2:从数据库加载记录,将属性从模型映射到 db 对象并保存更改,而不将绑定模型附加到上下文。

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

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