通过收集DTO来检测模型集合的变化

时间:2016-09-23 09:23:13

标签: c# entity-framework

我收藏了一些模特:

.....<div class="main-image">
<a title="" style="outline-style: none; text-decoration: none;" class="jqzoom" rel="gallery1" data-active="1" href="files/product/images/239_image_raw.jpg">
    <div class="zoomPad">
        <img style="opacity: 1;" title="" src="files/product/images/239_image.jpg" alt="ABSOLUTE SUMMER 8 VITA BASSA" height="320" width="240">
        <div style="top: 97.6167px; left: 80px; width: 148px; height: 153px; position: absolute; border-width: 1px; display: none;" class="zoomPup"></div>
        <div style="position: absolute; z-index: 5001; left: 239px; top: 0px; display: none;" class="zoomWindow">
            <div style="width: 312px;" class="zoomWrapper"><div style="width: 100%; position: absolute; display: none;" class="zoomWrapperTitle"></div>
            <div style="width: 100%; height: 320px;" class="zoomWrapperImage">
                <img src="files/product/images/239_image_raw.jpg" style="position: absolute; border: 0px none; display: block; left: -169.782px; top: -206.257px;">.....

DTO集合:

class Person
{
    public int Id {get;set;}
    public int Age {get;set;}
    public string Name {get;set;}
}

var collectionModel = new List<Person>{ ... };

所以,class PersonDto { public int Id {get;set;} public int Age {get;set;} public string Name {get;set;} public int RowNumber {get;set;} } var collectionDto = new List<PersonDto>{ ... }; 我从存储库(数据库)获得,collectionModel我从远程客户端获取。

是否有一种有效的方法来比较这些集合和“应用更改”(更新已更改的实体,删除不存在并添加新实体)collectionDto以将其保存在数据库中?

一个明显的选择 - “手动”比较集合,更新属性,创建和删除对象。但是这段代码变得重复了。

1 个答案:

答案 0 :(得分:2)

不,没有。如果要避免手动映射属性,可以将Person作为DTO传递,然后将其附加到实体框架上下文。在您的存储库中:

protected virtual void Merge(object modified, object attached)
{
    if (attached != modified)
        DB.Entry(attached).CurrentValues.SetValues(modified);
    else
        DB.Entry(modified).State = EntityState.Modified;
}

然后插入或更新:

public void UpdateSomething(Something obj)
{
    var attached = DB.Somethings.Single(x => x.ID == obj.ID);

    Merge(obj, attached);
    DB.SaveChanges();
}