比较.NET中的两个模型

Evg*_*kiy 0 .net c# asp.net-mvc-3

让我们有成像模型:

public class InheritModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string OtherData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我们有一个带View的控制器,代表这个模型:

private InheritModel GetAll()
{
    return new InheritModel
    {
        Name = "name1",
        Description = "decs 1",
        OtherData = "other"
    };
}

public ActionResult Index()
{
    return View(GetAll());
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以在View中编辑它,更改一些数据并发回到服务器:

[HttpPost]
public ActionResult Index(InheritModel model)
{
    var merged = new MergeModel();
    return View(merged.Merge(model, GetAll()));
}
Run Code Online (Sandbox Code Playgroud)

我需要做什么:

  • 在视图中我们有模型的再现
  • 用户更改内容并发布
  • 合并方法需要比较逐场发布的模型和以前的模型
  • Merge方法创建一个新的InheritModel,其中包含已发布模型中更改的数据,所有其他数据应为null

有人可以帮我制作这种Merge方法吗?

UPDATE(!)

这不是一项微不足道的任务.接近如:

public InheritModel Merge(InheritModel current, InheritModel orig)
{
    var result = new InheritModel();
    if (current.Id != orig.Id) 
    {
        result.Id = current.Id;
    }
}
Run Code Online (Sandbox Code Playgroud)

不适用.它应该是通用解决方案.我们在模型中有200多个属性.第一个模型是从DB的严格表格构建的.

Dar*_*rov 5

public InheritModel Merge(InheritModel current, InheritModel orig)
{
    var result = new InheritModel();
    if (current.Id != orig.Id) 
    {
        result.Id = current.Id;
    }
    if (current.Name != orig.Name) 
    {
        result.Name = current.Name;
    }
    ... for the other properties

    return result;
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用反射并遍历所有属性并设置它们的值:

public InheritModel Merge(InheritModel current, InheritModel orig)
{
    var result = new InheritModel();
    var properties = TypeDescriptor.GetProperties(typeof(InheritModel));
    foreach (PropertyDescriptor property in properties)
    {
        var currentValue = property.GetValue(current);
        if (currentValue != property.GetValue(orig))
        {
            property.SetValue(result, currentValue);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

显然,这仅适用于1级属性嵌套.

  • @EvgeniyLabunskiy,示例提供.此外,如果视图模型中有200个属性,则应考虑更改设计. (2认同)