开发者

Find out what fields are being updated

I'm using LINQ To SQL to update a user address. I'm trying to track what fields were updated.

The GetChangeSet() method just tells me I'm updating an entity, but doesn't tell me what fields.

What else do I need?

var item = context.Dc.Ecs_TblUserAddresses.Single(a => a.ID == updatedAddress.AddressId);

//ChangeSet tracking
item.Address1 = updatedAddress.AddressLine1;
item.Address2 = updatedAddress.AddressLine2;
item.Address3 = updatedAddress.AddressLine3;
item.City = up开发者_如何学GodatedAddress.City;
item.StateID = updatedAddress.StateId;
item.Zip = updatedAddress.Zip;
item.Zip4 = updatedAddress.Zip4;
item.LastChangeUserID = request.UserMakingRequest;
item.LastChangeDateTime = DateTime.UtcNow;

ChangeSet set = context.Dc.GetChangeSet();

foreach (var update in set.Updates)
{
    if (update is EberlDataContext.EberlsDC.Entities.Ecs_TblUserAddress)
    {

    }
}


Use ITable.GetModifiedMembers. It returns an array of ModifiedMemberInfo objects, one for each modified property on the entity. ModifiedMemberInfo contains a CurrentValue and OriginalValue, showing you exactly what has changed. It's a very handy LINQ to SQL feature.

Example:

ModifiedMemberInfo[] modifiedMembers = context.YourTable.GetModifiedMembers(yourEntityObject);

foreach (ModifiedMemberInfo mmi in modifiedMembers)
{
    Console.WriteLine(string.Format("{0} --> {1}", mmi.OriginalValue, mmi.CurrentValue));
}


You can detect Updates by observing notifications of changes. Notifications are provided through the PropertyChanging or PropertyChanged events in property setters.

E.g. you can extend your generated Ecs_TblUserAddresses class like this:

public partial class Ecs_TblUserAddresses
{
    partial void OnCreated()
    {
        this.PropertyChanged += new PropertyChangedEventHandler(User_PropertyChanged);
    }

    protected void User_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        string propertyName = e.PropertyName;
        // do what you want
    }
}

Alternatively, if you want to track a special property changing, you could use one of those OnPropertyNameChanging partial methods, e.g. (for City in your example):

partial void OnCityChanging(string value)
{
    // value parameter holds a new value
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜