【问题标题】:efcore change modified state to update entity is not working with sub data objectsefcore change modified state to update entity is not working with sub data objects
【发布时间】:2019-11-20 16:50:47
【问题描述】:

我使用此代码设置了一个通用存储库进行更新

private void AttachIfNot(TEntity entityToActive)
{
    if (_dbContext.Entry(entityToActive).State == EntityState.Detached)
    {
        _dbSet.Attach(entityToActive);
    }
}

private void UpdateEntity(TEntity entityToUpdate)
{
    AttachIfNot(entityToUpdate);
    _dbContext.Entry(entityToUpdate).State = EntityState.Modified;
}

它只是附加实体并将修改后的状态设置为保存。

但是当我使用 efocre ownsone 映射一个值对象时,更新实体功能不起作用。

我发现它只有在我将 Valueobject 设置为 modified 时才有效。

_dbContext.Entry(entityToUpdate).State = EntityState.Modified; 
_dbContext.Entry(entityToUpdate.Valueobject).State = EntityState.Modified; 

但我很难在通用存储库中指定所有值对象。

这是代码也有一对多或其他关系的问题。 工作方式是这样的:

Classroom classroom = new Classroom
{
    Id = 1,
    Name = "b",
    Students = new List<Student>
    {
        new Student()
        {
            Name = "aa",
            Id = 2
         }
    }
};

if (_defaultDbContext.Entry(classroom).State == EntityState.Detached)
{
    _defaultDbContext.Classrooms.Attach(classroom);
    foreach(var stu in classroom.Students)
    {
        _defaultDbContext.Students.Attach(stu);
    }
}

_defaultDbContext.Entry(classroom).State = EntityState.Modified;
foreach (var stu in classroom.Students)
{
    _defaultDbContext.Entry(stu).State  = EntityState.Modified;
}

_defaultDbContext.SaveChanges();

我发现一种方法是获取实体表单 repo,然后使用 automapper 更新它:

targetEntity = repo.GetById(entityId);
automapper.map(souceEntity,targetEntity);
//or
automapper.map(souceDto,targetEntity);
_dbContext.Save();

实体是通过查询来的,所以会跟踪变化。

但是当我想更改实体时,我必须使用此实体映射配置自动映射器

CreateMap<EntityType, EntityType>();

我认为这不是最好的解决方案。有没有更好的办法?

【问题讨论】:

    标签: entity-framework-core ef-core-3.0


    【解决方案1】:

    DbContext.Update 可以解决这个问题。 见:

    https://www.learnentityframeworkcore.com/dbcontext/change-tracker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 2021-04-22
      • 1970-01-01
      • 2022-12-02
      • 2017-03-03
      • 2017-09-22
      • 1970-01-01
      • 2022-12-26
      相关资源
      最近更新 更多