问题
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