How to null check on Money Field in C#?

守給你的承諾、 提交于 2019-12-11 05:33:36

问题


I want to null check for money field in .net MVC web services how to null check I write this but i don't get answer

//create module
public Money Amount { get; set; }

//Null Check
if ((EntityObject.Amount) != null)
{
    object Entity.Attributes.Add("budget amount", EntityObject.Amount);
}

How I write null check at Money field?


回答1:


Money is a special datatype, you have to handle like below using GetAttributeValue.

Money myMoneyField = (Money)EntityObject.GetAttributeValue<Money>(Amount);

decimal actualAmount;

if (myMoneyField != null)
{
    actualAmount = myMoneyField.Value;
}
else 
{ 
    actualAmount = 0; 
}

Entity.Attributes.Add("budget_amount", new Money(actualAmount));



回答2:


Entity.GetAttributeValue<T> Method (String) is good to avoid nulls, but please be careful that it will return Default values for some data types.

http://www.crmanswers.net/2015/04/getattributevalue-demystified.html https://msdn.microsoft.com/en-us/library/gg326129.aspx

if you are using Late bound Entity class, then you can do as below:

if ((EntityObject.Attributes.Contains("youMoneyFieldName")
{
   decimal moneyInDecimal = ((Money)EntityObject["youMoneyFieldName"]).Value;
   object Entity.Attributes.Add("budget amount", new Money(moneyInDecimal));
}

Before checking for null value, make sure you have retrieved the attribute in your Query like below:

// Retrieve the account containing several of its attributes.

ColumnSet cols = new ColumnSet(
    new String[] { "youMoneyFieldName" });

EntityObject retrievedEntity = (EntityObject)_serviceProxy.Retrieve("yourEntityName", GuidId, cols);

https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.iorganizationservice.retrieve.aspx



来源:https://stackoverflow.com/questions/48317336/how-to-null-check-on-money-field-in-c

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