ASP.NET Core-使用表单部分更新现有数据

发布于 2025-02-06 05:12:05 字数 255 浏览 2 评论 0原文

如何使用表单部分更新模型?换句话说,如何更新可能具有50个字段的模型数据库中的数据,但是我只想通过表单更新两个字段?我有一个具有形式的模型。该模型有30个字段,但我只想通过表格更新模型数据中的出生日期和描述。

我该怎么做,而不必事先从数据库中获取数据?

例如:

申请人有30个字段,但我只需要更新申请人的姓氏和出生日期,因此我的表格只有这些字段以进行更新。如何仅更新这两个字段而不擦除或使用其他两个字段使用默认值?这是视图模型吗?

谢谢你!

How do I update a model partially using a form? In other words, how do I update the data in a database for a model that may have 50 fields, but I only want to update two of them via a form? I have a model that has a form. That model has 30 fields, but I only want to update the date of birth and a description in the model's data through the form.

How do I do that without having to grab the data from the database beforehand?

For example:

Applicant has 30 fields, but I only need to update the Applicant's last name and date of birth, so my form ONLY has these fields in it for updating. How do I update JUST those two fields without wiping out or using default values for the others? Is that a view model?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原来是傀儡 2025-02-13 05:12:05

尝试附加方法。您将需要为实体和标记字段设置主键,您需要更新作为修改

var entity = new SomeEntity()
{
    Id = id, // primary key
    SomeProperty = newvalue,
};

dbContext.SomeEntities.Attach(entity);
dbContext.Entry(entity).Property(x => x.SomeProperty).IsModified = true;
dbContext.SaveChanges();

Try Attach method. You will need to set primary key for the entity and mark fields you need to update as modified

var entity = new SomeEntity()
{
    Id = id, // primary key
    SomeProperty = newvalue,
};

dbContext.SomeEntities.Attach(entity);
dbContext.Entry(entity).Property(x => x.SomeProperty).IsModified = true;
dbContext.SaveChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文