How to update a CRM 2011 Entity using LINQ in a Plugin?

南笙酒味 提交于 2019-11-30 23:02:38

问题


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();

回答1:


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();




回答2:


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.




回答3:


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);
}
    }


来源:https://stackoverflow.com/questions/5074833/how-to-update-a-crm-2011-entity-using-linq-in-a-plugin

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