【问题标题】:ASP.Net MVC TryUpdateModel() equivalent for using in a Windows ApplicationASP.Net MVC TryUpdateModel() 等效于在 Windows 应用程序中使用
【发布时间】:2019-12-09 10:14:01
【问题描述】:

TryUpdateModel 是 System.Web.Mvc 中的方法之一,但我需要在没有此库的 windows 应用程序中使用它。 EF中的任何类似方法或其他建议,以便我可以在不与目标模型一一匹配字段的情况下更新实体?

【问题讨论】:

  • 非常重要的问题。谢谢你

标签: c# .net asp.net-mvc entity-framework


【解决方案1】:

我尝试了很多解决方案,但最后我通过反射编写了自己的方法,这对我来说非常适合,如下所示:

        public void TryUpdateModel<T>(T existingModel, T newModel)
    {
        PropertyInfo[] properties = existingModel.GetType()
                                                .GetProperties()
                                                .Where(pi => !(pi.PropertyType.IsSubclassOf(typeof(T))))
                                                .ToArray();
        foreach (var item in properties)
        {
            var propName = item.Name;
            if (item.PropertyType.IsSealed && item.PropertyType.IsSerializable && item.Name != existingModel.GetType().Name + "Id")
            {
                var newValue = db.Entry(newModel).Property(propName).CurrentValue;
                db.Entry(existingModel).Property(propName).CurrentValue = newValue;
            }
        }
    }

它有 2 个模型(因为它们是通用类,但应该是相同的),其中第一个是从数据库中获取的模型,第二个是从 UI 表单提交的模型。 它将除导航属性和主键之外的属性值从 newModel 更新到 existingModel,以便实体框架意识到值已更改并且必须更新。

【讨论】:

  • 答案不应仅包含指向外部资源的链接。将相关信息复制到您的答案中,以便在外部资源消失时答案仍然有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多