CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

EF4 Insert, Update, Delete in a WCF method

1189 Views
Copy Code Show/Hide Line Numbers
[OperationContract]
public Contact SaveContact(Contact entity)
{
    bool _IsDeleted = false;
 
    string _EntitySetName;
    _EntitySetName = "Contacts";
 
    using (CometEntities _Context = new CometEntities())
    {
        switch (entity.ChangeTracker.State)
        {
            case ObjectState.Deleted:
                //delete
                _IsDeleted = true;
                _Context.AttachTo(_EntitySetName, entity);
                _Context.DeleteObject(entity);
                break;
            default:
                //everything else
                _Context.Contacts.ApplyChanges(entity);
                break;
        }
 
        try
        {
            // Try to save changes, which may cause a conflict.
            _Context.SaveChanges(System.Data.Objects.SaveOptions.None);
        }
        catch (System.Data.OptimisticConcurrencyException)
        {
            // Resolve the concurrency conflict by refreshing the 
            // object context before re-saving changes. 
            _Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, entity);
 
            // Save changes.
            _Context.SaveChanges();
        }
    }
 
    if (_IsDeleted)
        return null;
    entity.AcceptChanges();
    return entity;
}
by Jerry Nixon
  June 30, 2010 @ 10:33pm
Tags:
Description:
Save a Contact (http://jerrytech.blogspot.com/2010/06/ef4-insert-update-delete-in-wcf-method.html)

by Jerry Nixon    May 05, 2011 @ 2:41pm

Updated 5/5/2011

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate