11

We are able to create new entities without any issues, but updating an existing entity in a plugin this does not appear to be working. This is for CRM 2011.

var crmContext = new CustomCrmContext(service);

var contact = crmContext.Contact.FirstOrDefault(c=>c.Id == targetEntity.Id);

contact.new_CustomField = "Updated";

crmContext.SaveChanges();

3 Answers 3

15

No need to download the whole Contact record if you already have the Id and you just need to update a field or two. You also don't need the OrganizationServiceContext - just the Service. Try something like:

var c = new contact() {
  Id = targetEntity.Id,
  new_CustomField = "Updated"
}

service.Update(c);

This will save the roundtrip of querying for the contact first.

Sign up to request clarification or add additional context in comments.

1 Comment

If you have previously fetched the entity from a OrganizationServiceContext, and you then query for it again. Won't it be already be cached in the context, i.e. no roundtrip will be performed?
14

You have to mark the object as modified in order to get it submitted to the server. See OrganizationServiceContext.UpdateObject (Entity)

You should add crmContext.UpdateObject(contact); before crmContext.SaveChanges();

9 Comments

<Message>Unexpected exception from plug-in (Execute): Microsoft.Xrm.Sdk.SaveChangesException: An error occured while processing this request.</Message>
Above is what I get when I do an UpdateObject. Again, I can add a new record without any issue. It is just updating an existing object that doesn't seem to be working. Any ideas?
Can you please describe how you registered your plugin? Is it registered for update of contact? The SaveChangesException has a property "Results" - which items are included?
I had the same problem. After I added context.UpdateObject(entity) before context.SaveChanges() it worked.
I have the same results that @Chad, any suggestions?
|
1

LINQ is fine, just create the new object or list and loop the list in the linq and update:

using (var crm = new XrmServiceContext(service)){
var foo = crm.nmipcs_productpriceitemSet
    .Where(ppis => ppis.nmipcs_Account.Id == account.Id).ToList();

foreach (var nmipcsProductpriceitem in foo){
    var f = new nmipcs_productpriceitem
    {
    Id = nmipcsProductpriceitem.Id                 
    ,
    nmipcs_PriceSalesChannel = (decimal) 9.99
    };

    service.Update(f);
}
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.