存储库模式更新实体并设置独占 属性
Repository Pattern Update Entity and set exclusive property
我正在使用带有工作单元的通用存储库模式。我正在更新记录,我有一列存储记录的状态,它不是来自视图本身。因此,当我更新记录时,我只想从存储库中设置该值,但我不能获取实体的属性。这是我更新记录的示例代码。
T 有 isDeleted 属性 并且它为空,但我想在此处设置该值。
我该怎么做?
public void QuickUpdate(T original, T updated)
{
_dbSet.Attach(original);
_context.Entry(original)
.CurrentValues
.SetValues(updated);
_context.Entry(original).State = EntityState.Modified;
}
我不知道你的对象模型,但我正在做我能做的最简单的例子。让我们假设一个 Record
类型代表你的 T
和一个 Id
属性 代表一个键。
public void QuickUpdate(Record original)
{
Record updatedRecord = _dbSet.Records.FirstOrDefault(r => r.Id == original.Id);
updateRecord.IsDeleted = true;
_dbSet.SaveChanges();
}
我不太理解你关于 original
和 updated
如何一起玩的问题,但是在实体上设置单个 属性 就这么简单。
答案在这里。
-- 已更新。
var originalStatus = original.GetType().GetProperty("isDeleted").GetValue(original);
updated.GetType().GetProperty("isDeleted").SetValue(original, true);
_dbSet.Attach(original);
_context.Entry(original)
.CurrentValues
.SetValues(updated);
_context.Entry(original).State = EntityState.Modified;
我正在使用带有工作单元的通用存储库模式。我正在更新记录,我有一列存储记录的状态,它不是来自视图本身。因此,当我更新记录时,我只想从存储库中设置该值,但我不能获取实体的属性。这是我更新记录的示例代码。 T 有 isDeleted 属性 并且它为空,但我想在此处设置该值。 我该怎么做?
public void QuickUpdate(T original, T updated)
{
_dbSet.Attach(original);
_context.Entry(original)
.CurrentValues
.SetValues(updated);
_context.Entry(original).State = EntityState.Modified;
}
我不知道你的对象模型,但我正在做我能做的最简单的例子。让我们假设一个 Record
类型代表你的 T
和一个 Id
属性 代表一个键。
public void QuickUpdate(Record original)
{
Record updatedRecord = _dbSet.Records.FirstOrDefault(r => r.Id == original.Id);
updateRecord.IsDeleted = true;
_dbSet.SaveChanges();
}
我不太理解你关于 original
和 updated
如何一起玩的问题,但是在实体上设置单个 属性 就这么简单。
答案在这里。 -- 已更新。
var originalStatus = original.GetType().GetProperty("isDeleted").GetValue(original);
updated.GetType().GetProperty("isDeleted").SetValue(original, true);
_dbSet.Attach(original);
_context.Entry(original)
.CurrentValues
.SetValues(updated);
_context.Entry(original).State = EntityState.Modified;