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

标签 c# entity-framework

我收集了一些模型:

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

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

和 DTO 的集合:

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 我从远程客户端获取。

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

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

最佳答案

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

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();
}

关于c# - 通过收集 DTO 来检测模型集合的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39657193/

相关文章:

c# - 使用 Expression 调用属性和对象并判断对象是否为 null

c# - 如何在 C# 中获取 PSObject.Properties 的 ScriptProperty 值?

c# - 如何在不等待事件监听器运行的情况下触发事件?

c# - 在 EF 中保存对象时,不会在数据库中建立新的多对多连接

c# - Entity Framework - 多项目支持

c# - 在 Python 中使用 System.Collections.Generic.List`1[System.Byte]

c# - Entity Framework : Loading 2nd level navigation properties

.net - Entity Framework 函数导入参数类型在从数据库更新模型时重置

c# - LINQ:如何清空投影中的属性?

c# - 如何克服从 API 中提取大型 xml 文档的 OutOfMemoryException?