jru*_*ell 9 entity-framework ef-code-first entity-framework-4.1
我试图弄清楚如何将已分离实体的特定属性标记为已修改.如果我执行以下操作,它将标记所有已修改的属性,并且生成的sql将更新所有列.
/// <summary>
/// Sets the entity in the modified state.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity">The entity.</param>
void IDbContext.Modified<T>(T entity)
{
DbEntityEntry<T> entry = Entry(entity);
if (entry.State == EntityState.Modified)
{
// if the state is already Modified we don't need to do anything else
return;
}
if (entry.State == EntityState.Detached)
{
Set<T>().Attach(entity);
//TODO: set specific properties modified instead of the the whole object.
entry.State = EntityState.Modified;
}
}
Run Code Online (Sandbox Code Playgroud)
如何仅将已更改的属性设置为已修改?
我试图在一个实现DbContext将由通用存储库使用的类中使用它.目标是自动确定哪些属性与数据库值相比已更改,然后将这些已更改的属性状态设置为"已修改".在我当前的实现中,Modified方法不知道实体类型,所以我不能简单地用它来检索它context.Set<T>.Find(key).
我想我可以添加一个接受originalEntity参数的重载,但是如果可能的话我宁愿不这样做.
void IDbContext.Modified<T>(T entity, T originalEntity)
{
DbEntityEntry<T> entry = Entry(entity);
if (entry.State == EntityState.Modified)
{
// if the state is already Modified we don't need to do anything else
return;
}
if (entry.State == EntityState.Detached)
{
Set<T>().Attach(entity);
entry.OriginalValues.SetValues(originalEntity);
}
}
Run Code Online (Sandbox Code Playgroud)
Lad*_*nka 13
您必须通过调用手动为每个属性执行以下操作:
DbEntityEntry<T> entry = context.Entry(entity);
if (entry.State == EntityState.Detached)
{
context.Set<T>().Attach(entity);
entry.Property(e => e.SomeProperty).IsModified = true;
// TODO other properties
}
Run Code Online (Sandbox Code Playgroud)
编辑:
以前的示例假设您不想从数据库重新加载实体,在这种情况下,您必须知道哪些属性已更改 - 由您来实现它.
如果您对数据库的其他查询感到满意,可以使用:
var persistedEntity = context.Set<T>.Find(key);
var entry = context.Entry(persistedEntity);
entry.CurrentValues.SetValues(entity);
Run Code Online (Sandbox Code Playgroud)
EDIT2:
设置原始值应该是反向操作(但我从未尝试过这个):
var persistedEntity = context.Set<T>.Find(key);
context.Entry(persistedEntity).State = EntityState.Detached;
var entry = context.Entry(entity);
context.Set<T>.Attach(entity);
// I'm not sure if you have to change the state of the entity
entry.OriginalValues.SetValues(persistedEntity);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9288 次 |
| 最近记录: |