gpt4 book ai didi

asp.net-mvc - 使用 Entity Framework 和 ASP.NET MVC 更新实体的单个属性

转载 作者:行者123 更新时间:2023-12-05 02:24:54 24 4
gpt4 key购买 nike

我正在尝试在 ASP.NET MVC 网络应用程序中使用 Entity Framework 。

假设我有一个实体“people”,带有一些图形细节。

我的 Web 应用程序有一个 View ,我可以使用 Ajax 一个一个地更改我的详细信息。

例如,我可以使用 Ajax post 仅更改我的实体的“名称”。

在我的 Controller 中实现一个方法来对我的“人”实体执行此更新的最佳实践是什么?我想创建一个通用的“更新”方法,而不是每个属性的特定方法。

谢谢你帮助我

最佳答案

public ActionResult Update(int id, string propertyName, object propertyValue)
{
using(var ctx = new Db())
{
var person = ctx.People.First(n => n.Id == id);
Type t = person.GetType();
PropertyInfo prop = t.GetProperty(propertyName);
prop.SetValue(person, propertyValue, null);
ctx.SaveChanges();
}
return Json(new { Success = true });
}

关于asp.net-mvc - 使用 Entity Framework 和 ASP.NET MVC 更新实体的单个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com