2012-07-11 63 views
0

我正在尝试将更改记录到数据库,以便用户可以查看谁更改了哪些内容。我正在使用DbEntityEntry来检查并记录已修改的DbPropertyEntity。当我想要将更改记录到导航属性时,我遇到了问题。我使用Reference()方法来获得对导航属性的引用,但不像DbPropertyEntity,DbReferenceEntry没有OriginalValue只有CurrentValue属性。你如何获得导航属性的OriginalValueDbPropertyEntry获取原始值

//Get the field that hold the id of the foreign key 
var field = entry.Property(x => x.field); 

//Check to see if the user changed the value 
if (field.IsModified) 
{ 
    //Get the reference property associated with the field 
    var fieldRef = entry.Reference(x => x.fieldRef); 

    //Log the id change 
    Log(field.Name, field.CurrentValue, field.OriginalValue); 

    //Can't get the OriginalValue 
    Log(fieldRef.Name, fieldRef.CurrentValue, ???); 
} 

回答

1

你期望记录什么参考?

如果要记录关系中的更改(=外键中的更改),则应将外键映射为单独的属性,并将其记录为普通字段。如果你没有映射外键,你有一个independent association。支持DbContext API is limited中的独立关联。完全支持仅在ObjectContext API中(您可以从DbContext API使用它),但它仍不能解决您的问题 - 独立关联无法处于修改状态。它可以保持不变,添加或删除状态。如果您更改引用,则旧关联标记为已删除,并添加新内容=有两个单独的关联对象由上下文跟踪。

+0

我没有使用edmx工具,我只是创建了一个数据库并添加了字段,然后更新了我的域对象。我正在记录外键更改。问题是用户会看到这个日志键的变化没有意义(例如TypeID从3改为4),我需要在导航属性中记录更改(例如Type从Student值更改为老师)。 – 2012-07-11 20:56:10