Dynamics CRM 365 - 零基礎入門學習後端外掛語法總結(樣例使用方法)

Even-LittleMonkey發表於2020-11-16

Dynamics CRM 365 - 零基礎入門學習後端外掛語法總結(樣例使用方法)

整理下平時CRM開發中用到的一些基本的外掛語法,或許對初學Dynamics的新手有所幫助

  1. 外掛必寫文
public IPluginExecutionContext context = null;//上下文
public IOrganizationServiceFactory serviceFactory = null;//組織服務工廠物件
public IOrganizationService service = null;//Org服務物件
 //建立執行上下文
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
//建立組織服務工廠物件
serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
//Org服務物件
service = serviceFactory.CreateOrganizationService(context.UserId);
//觸發當前外掛的那條記錄
Entity entity= service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true));
  1. 獲取當前實體對應的查詢型別id與實體
//獲取當前實體的查詢型別欄位的id
Guid guid = ((EntityReference)entity["查詢欄位名稱"]).Id;
//方法二
Guid guid = entity.GetAttributeValue<EntityReference>("查詢欄位名稱").Id;
//根據當前id去new出查詢欄位的實體
Entity entityMember = new Entity("對應的實體名稱", guid);
  1. 獲取選項集型別
OptionSetValue optionSet = (OptionSetValue)entity["選項集欄位"];
  1. 接收bool型別
bool result=entity.GetAttributeValue<Boolean>("兩個選項欄位名稱");
  1. 小數取整對欄位賦值
//將小數字段取出轉換為double型別
double sum= ((double)entity["小數字段名稱"]);
//小數四捨五入
EntityName["FileName"] = int.Parse(Math.Round(sum).ToString());
  1. 實體時間欄位加一年賦值
EntityName["FileName"] = Convert.ToDateTime(entity["時間欄位"]).AddYears(1);
  1. 查詢(自定義)
//建立查詢表示式
QueryExpression query = new QueryExpression("實體名稱");
//設定顯示的列
query.ColumnSet = new ColumnSet(new string[] { "列1", "列2", "列3"});
//建立條件表示式,查詢會員id對應的積分賬戶
ConditionExpression condition = new ConditionExpression()
{
    //條件等於那一列
      AttributeName = "列名",
     Operator = ConditionOperator.Equal
};
//列名的條件,等於的id
condition.Values.Add(id);
//將條件表示式繫結到查詢表示式上
query.Criteria.AddCondition(condition);
//獲取查詢結果集合
EntityCollection collection = service.RetrieveMultiple(query);
  1. 查詢2(根據篩選配置)
string detailwhere= "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
detailwhere+= "<entity name='hy_jinhuodetails'>";
detailwhere+= "<attribute name='hy_jinhuodetailsid' />";
detailwhere+= "<attribute name='hy_name' />";
detailwhere+= "<attribute name='createdon' />";
detailwhere+= "<order attribute='hy_name' descending='false' />";
detailwhere+= "<filter type='and'>";
detailwhere+= "<condition attribute='hy_jinhuoname' operator='eq' uiname='"+currentEntity["hy_name"] +"' uitype='hy_jinhuo' value='"+currentEntity.Id+"' />";
detailwhere+= "</filter>";
detailwhere+= "</entity>";
detailwhere+= "</fetch>";
//建立條件表示式
FetchExpression condition = new FetchExpression(detailwhere);
//根據條件查詢查詢符合的entity集合
DataCollection<Entity> select = service.RetrieveMultiple(condition).Entities;

小Monkey還會不斷補充的

到此就結束啦,快去練習一下吧!歡迎大佬和小Monkey溝通。
在這裡插入圖片描述

感謝大佬指正 小Monkey
如果你覺得有用的話,就留個贊吧!蟹蟹

相關文章