How to null check on Money Field in C#?

2019-07-23 23:15发布

问题:

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