Finding the Changeset in Entity Framework

邮差的信 提交于 2019-12-12 20:57:49

问题


I am using EF4 repositories in a ASP.NET MVC3/WCF application. I am using the Unit of Work pattern to apply changes to the database

One of the user requirements is to create a ticket/email with a list of changes to the entity. Is there a way I can detect only the changed properties on an entity in the following function?

public void UpdateTrackedEntity<T>(T modifiedEntity) where T : class
{
    var set = CreateObjectSet<T>();
    set.ApplyCurrentValues(modifiedEntity);
}

回答1:


Yes there is a way:

public void UpdateTrackedEntity<T>(T modifiedEntity) where T : class
{
    var set = CreateObjectSet<T>();
    set.ApplyCurrentValues(modifiedEntity);
    var entry = ObjectStateManager.GetObjectStateEntry(modifiedEntity);
    // entry has two collections: CurrentValues (those you applied) and 
    // OriginalValues (those loaded from DB)
    // It also have method GetModifiedProperties to get collection of modified 
    // property names.
}

Check ObjectStateEntry for more details.




回答2:


Suppose that your domain service object is DsrvObj

 DsrvObj.EntityContainer.GetChanges() 
                      ...GetChanges().AddedEntities.Count /*also possible for modified and romoved ones*/

//These ones could be beneficial also

           DsrvObj.HasChanges
           DsrvObj.MS_EntitySets.HasChanges

will give you the changeset, But interestingly I can't see some modified boolean fields on this changeset today! Finally I realized that for instance if a DataGrid is in EditMode your changes doesnt go to changeset,After end edit it goes to changeset.

implement it ,test it ,Trust it!



来源:https://stackoverflow.com/questions/5806510/finding-the-changeset-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!