試圖比較實體與當前日期的現有日期。如果實體(testentity)日期的實體字段(testfield)在當前日期之後等於OR,則將字段中的日期添加1年。比較,添加和更新實體中的日期字段
問題 - 出於某種原因,它讀取所有日期並進行比較,但在現場不進行更新。我已經在實體上使用了後操作步驟。
更新:我添加ServiceContext.UpdateObject(實體)和ServiceContext.SaveChanges();代碼,但現在它給我「上下文不是正在跟蹤...」的錯誤。
任何幫助將深表謝意。謝謝!
請看下面的代碼。
public class PostUpdate: Plugin
{
public PostUpdate()
: base(typeof(PostUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "new_testentity", new Action<LocalPluginContext>(ExecutePostUpdate)));
protected void ExecutePostupdate(LocalPluginContext localContext)
{
// get the plugin context
IPluginExecutionContext context = localContext.PluginExecutionContext;
//Get the IOrganizationService
IOrganizationService service = localContext.OrganizationService;
//create the service context
var ServiceContext = new OrganizationServiceContext(service);
ITracingService tracingService = localContext.TracingService;
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "new_testentity")
return;
try
{
var k = entity["new_testfield"];
DateTime m = Convert.ToDateTime(k);
DateTime d = DateTime.Now;
int result = DateTime.Compare(m, d);
// compare the dates
if (result <= 0)
{
try
{
entity["new_testfield"] = DateTime.Now.AddYears(1);
ServiceContext.UpdateObject(entity);
}
ServiceContext.SaveChanges();
//Adding this is giving me "The context is not currently tracking the 'new_testentity' entity."
}
catch (FaultException<OrganizationServiceFault> ex)
{
}
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
Gregg,非常感謝您的意見。我在註冊前註冊了插件。 'if(context.InputParameters.Contains(「Target」)&& context.InputParameters [「Target」] is Entity) { //從輸入的參數表中獲取目標實體。 實體實體=(實體)context.InputParameters [「目標」];'應該在這之後?還應該在這裏添加條件?對不起,我有點失落如何做到這一點。我會非常感謝你的幫助! – cashbowl
您是否指Renaud在本帖子中發表的評論? http://stackoverflow.com/questions/8167571/crm-2011-how-to-update-record-in-a-create-plugin?answertab=active#tab-top – cashbowl
@cashbowl:找出答案的一種方法- 試試看!但是這個解決方案應該適合你。 –