【问题标题】:Mocking DbEntityEntry.CurrentValues.SetValues() in EF4 CTP5 Code First在 EF4 CTP5 Code First 中模拟 DbEntityEntry.CurrentValues.SetValues()
【发布时间】:2011-07-21 13:26:21
【问题描述】:

我正在尝试使用 DbEntityEntry.CurrentValues.SetValues() 方法来促进使用来自非实体 DTO 的值更新现有实体(请参阅:http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx

我在删除对 DbEntityEntry 的依赖时遇到了麻烦(用于模拟、测试)。这是我想做的一个例子:

var entity = dbSet.Find(dto.Id);
var entry = context.Entry(entity);
entry.CurrentValues.SetValues(dto);
context.SaveChanges();

我也考虑过:

EntityType entity = new EntityType() { Id = dto.Id };
context.Attach(entity);
var entry = context.Entry(entity);
entry.CurrentValues.SetValues(entity);
context.SaveChanges();

在使用实际 DbContext 时,我发现两者似乎都是合理的,但是当我将上下文抽象为 IMyContext 时,我失去了为实体获取 DbEntityEntry 的能力,因此失去了 SetValues 选项。

有什么办法可以解决这个问题,还是我需要硬着头皮从 DTO 中手动设置实体的修改属性(对于具有许多属性的实体来说,可能有很多样板文件)?

(我对 EF 还很陌生,这是我的第一个 StackOverflow 问题,所以请温柔)

【问题讨论】:

    标签: entity-framework-ctp5 ef4-code-only


    【解决方案1】:

    如果您以前从未使用过它,那么 AutoMapper(也可通过 NuGet 获得)将是一个很好的用途。我不知道如何解决您的 IMyContext 问题,并且还会求助于映射属性。但我不会手动执行此操作,而是允许 AutoMapper 完成繁重的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      相关资源
      最近更新 更多