gpt4 book ai didi

c# - Entity Framework 如何首先正确更新实体代码?

转载 作者:太空狗 更新时间:2023-10-30 00:26:00 26 4
gpt4 key购买 nike

我的通用存储库中有以下更新方法

public class Repository<T> : IRepository<T> where T : class
{
private readonly DbSet<T> _dbSet;
public virtual T Update(T item) {
return _dbSet.Attach(item);
}
}

UnitOfWork 有一个在上下文中调用 SaveChanges 的提交方法。更多详情在这里
https://codereview.stackexchange.com/questions/19037/entity-framework-generic-repository-pattern

当我更新一个实体然后调用

ProductRepository.Update(modifiedProduct);
UnitOfWork.Commit;

没有任何内容会流入数据库。

但是,仅调用 Commit 即可(不调用更新方法)。

那么,Attach Method 做了什么导致更改不会向下流到数据库。我认为附加调用是在更新方法中进行的正确调用。那么,是什么导致了意外行为。

来自 CodePlex 上的 EF 源代码

/// <summary>
/// Attaches the given entity to the context underlying the set. That is, the entity is placed
/// into the context in the Unchanged state, just as if it had been read from the database.
/// </summary>
/// <param name="entity"> The entity to attach. </param>
/// <returns> The entity. </returns>
/// <remarks>
/// Attach is used to repopulate a context with an entity that is known to already exist in the database.
/// SaveChanges will therefore not attempt to insert an attached entity into the database because
/// it is assumed to already be there.
/// Note that entities that are already in the context in some other state will have their state set
/// to Unchanged. Attach is a no-op if the entity is already in the context in the Unchanged state.
/// </remarks>
public object Attach(object entity)
{
Check.NotNull(entity, "entity");

InternalSet.Attach(entity);
return entity;
}

最佳答案

///     Attach is used to repopulate a context with an entity that is known to already exist in the database.
/// SaveChanges will therefore not attempt to insert an attached entity into the database because
/// it is assumed to already be there.
/// Note that entities that are already in the context in some other state will have their state set
/// to Unchanged.

附加实体后,状态将保持不变,因此不会为该实体触发更新 sql。您需要在附加后手动设置实体的状态。

关于c# - Entity Framework 如何首先正确更新实体代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13949202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com