【问题标题】:Update model with TryUpdateModel in ASP.NET MVC Core Web API and Entity Framework Core doesn't work在 ASP.NET MVC Core Web API 和 Entity Framework Core 中使用 TryUpdateModel 更新模型不起作用
【发布时间】:2017-05-15 13:31:11
【问题描述】:

我是 ASP.NET MVC Core Web API 和 EF Core 的新手,我正在创建一个简单的 MVC Web API 演示,如下所示。

[HttpPut("{id}")]
public async void Put(int id, [FromBody]Student student)
    {
        if (ModelState.IsValid)
        {
            var stu = _context.Students
                .Where(s => s.StudentId == id)
                .SingleOrDefault();

            var updateResult = await TryUpdateModelAsync<Student>(stu, "", s => s.FirstName, s => s.LastName, s => s.EnrollmentDate);
            _context.SaveChanges();
        }

    }

问题是TryUpdateModelAsync 不起作用,更改没有更新到数据库中。

我想知道:

  1. 如果TryUpdateModelAsync可以在MVC Web API中使用?

  2. 我真的不想写像下面这样无聊的代码,如何避免从一个对象到另一个相同类型的对象进行属性值设置? (这是我使用TryUpdateModelAsync的第一个原因)

    stu.FirstName = student.FirstName;
    stu.LastName = student.LastName;
    stu.SomeOtherProperties = student.SomeOtherProperties;
    _context.SaveChanges();
    

.NET Core 版本:1.1.0

ASP.Net Core 版本:1.1.0

实体框架核心版本:1.1.0

【问题讨论】:

  • public async void Put(int id, [FromBody]Student student) 可能是罪魁祸首,也许尝试返回一个任务?

标签: asp.net-core-mvc entity-framework-core asp.net-core-webapi


【解决方案1】:

Web API 一般使用DTO official docs 显示正确的方法。

请参阅GitHub issue TryUpdateModelAsync() doesn't work for ASP.NET Core MVC Web API 以获得明确的答案。

[FromBody] 属性使用格式化程序将请求正文反序列化为对象(例如,使用 JSON 或 XML)。

另一方面,模型绑定(包括TryUpdateModel API)使用值提供程序从表单主体(如果有)、查询字符串、路由数据或其他一些地方获取数据。

这里有几种方法:

  1. 您当然可以编写“无聊”的代码。或者您可以考虑使用 AutoMapper 等自动执行“左手/右手”操作的库。
  2. 您可以将发布的数据更改为表单发布,在这种情况下,模型绑定可以正常工作。
  3. 您可以更改发布的数据以使用 JSON PATCH 协议,该协议正是为此场景创建的。有一篇很棒的博客文章介绍了如何使用 ASP.NET Core 做到这一点:http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates

【讨论】:

    【解决方案2】:

    尝试从你的身体而不是你抬头的那个传递学生实例。

     public async void Put(int id, [FromBody]Student student)
        {
            if (ModelState.IsValid)
            {
                student.StudentId = id; // If the ID isn't passed in or you could validate that it matches the id passed in
                var updateResult = await TryUpdateModelAsync<Student>(student, "", s => s.FirstName, s => s.LastName, s => s.EnrollmentDate);
                _context.SaveChanges();
            }
        }
    

    【讨论】:

      【解决方案3】:

      FromBody 使用格式化程序将请求正文反序列化为 JSON 对象。

      TryUpdateModelAsync 依赖于模型绑定并使用值提供者来获取数据。

      您可以将发布的数据更改为使用模型绑定的表单帖子。

      【讨论】:

      • TryUpdateModelAsync 在 WebAPI 上不起作用,所以我改用 AutoMapper。
      【解决方案4】:

      这是一种执行从一个模型到另一个模型的基本更新的方法,如果任何属性更新失败,它将返回 false,否则返回 true。我怀疑TryUpdateModelAsync 可能会执行额外的工作,但至少对我来说这已经足够了。

      您需要添加using System; 和using System.Linq.Expressions;。除此之外,只需粘贴到您要从中使用它的类中。我在我的自定义控制器类中使用它,以便我可以在我的所有派生控制器中以类似于TryUpdateModelAsync 的方式使用它。

      /// <summary>
      /// Updates the destination model instance using values from the source model
      /// </summary>
      /// <typeparam name="TModel">The type of model to update</typeparam>
      /// <param name="source">The model containing the values to use</param>
      /// <param name="destination">The model to update</param>
      /// <param name="properties">The properties of the model to update</param>
      public static bool TryUpdateModel<TModel>(TModel source, TModel destination, params Expression<Func<TModel, object>>[] properties) where TModel : class
      {
          var ok = true;
      
          foreach (var prop in properties)
          {
              try
              {
                  string propertyName = string.Empty;
      
                  if (prop.Body is MemberExpression member)
                      propertyName = member.Member.Name;
                  else if (prop.Body is UnaryExpression unary)
                      propertyName =((MemberExpression)unary.Operand).Member.Name;
      
                  if (string.IsNullOrWhiteSpace(propertyName))
                  {
                      ok = false;
                      continue;
                  }
      
                  var input = source.GetType().GetProperty(propertyName).GetValue(source, null);
      
                  destination.GetType().GetProperty(propertyName).SetValue(destination, input);
              }
              catch
              {
                  ok = false;
              }
          }
      
          return ok;
      }
      

      在您的情况下,用法如下。您可能不需要 &lt;student&gt; 部分,但为了完整起见,我已将其包含在内。

      var updateResult = TryUpdateModel<Student>(student, stu, 
          s => s.FirstName, 
          s => s.LastName, 
          s => s.EnrollmentDate
      );
      

      【讨论】:

        猜你喜欢
        • 2020-09-25
        • 2022-09-28
        • 1970-01-01
        • 2018-04-12
        • 2018-02-12
        • 1970-01-01
        • 2023-03-14
        • 2017-09-30
        • 1970-01-01
        相关资源
        最近更新 更多