microsoft/Power-Fx

Type coersion issues

MarkMpn opened this issue · 0 comments

I'm trying to use Power Fx to calculate values that I can then use in an SDK app to update Dataverse records. I want to check that a formula will produce values of the expected type for each attribute, and use the built-in type coersion to do conversions where necessary.

I'm getting the expected type by first getting the record type of the target entity, then getting the type of the field within it, e.g.:

var connection = SingleOrgPolicy.New(org);
var recordType = connection.GetRecordType("contact");
var attributeType = recordType.GetFieldType("gendercode");

I can also get the type that will be produced by the formula, e.g.:

var checkResult = scope.Check("'Gender (Contacts)'.Female");

To check if the types are compatible I'm using:

if (!checkResult.ReturnType.CanPotentiallyCoerceTo(attributeType))
{
  throw new ...
}

In most cases this works well, but it seems to throw a StackOverflowException for optionset types like this. I can work around this by changing this check to:

if (!checkResult.ReturnType.Equals(attributeType) && !checkResult.ReturnType.CanPotentiallyCoerceTo(attributeType))
{
  throw new ...
}

but it would be good if CanPotentiallyCoerceTo worked consistently.

Once I've actually evaluated the formula and got a value I then need to actually do the coersion. In most cases I can do:

var eval = checkResult.GetEvaluator();
var result = eval.Eval(runtimeConfig);

if (!result.TryCoerceTo(attributeType, out var convertedValue))
{
  throw new ...
}

However, this again doesn't work for optionset values, or for lookups. I can work around this by adding various special cases for different result types but it would be cleaner if this was wrapped up within the TryCoerceTo method.