Managing configuration values that differ across environments, such as development, testing, and production, is essential, and environment variables make this easier. While accessing them in Power Automate or Canvas app is straightforward, it’s equally simple to retrieve them in a Dataverse plugin as well.
How Environment Variables Are Stored?
Environment variables are stored in two related Dataverse tables:
- environmentvariabledefinition – defines the variable schema, name, and default value.
- environmentvariablevalue – stores the actual value assigned for a specific environment.
Sample code
To retrieve these variables, we can perform a single query using a join to simultaneously get both the variable definitions and their corresponding values.
// Create a private dictionary to store environment variables
private Dictionary<string, string> environmentVariables = new Dictionary<string, string>();
private void GetEnvironmentVariables(params string[] schemaNames)
{
try
{
var query = new QueryExpression("environmentvariabledefinition")
{
ColumnSet = new ColumnSet("schemaname", "defaultvalue", "environmentvariabledefinitionid"),
LinkEntities =
{
new LinkEntity
{
JoinOperator = JoinOperator.LeftOuter,
LinkFromEntityName = "environmentvariabledefinition",
LinkFromAttributeName = "environmentvariabledefinitionid",
LinkToEntityName = "environmentvariablevalue",
LinkToAttributeName = "environmentvariabledefinitionid",
Columns = new ColumnSet("statecode", "value", "environmentvariablevalueid"),
EntityAlias = "ev"
}
}
};
query.Criteria.AddCondition("schemaname", ConditionOperator.In, schemaNames);
var entities = service.RetrieveMultiple(query).Entities;
foreach (var def in entities)
{
var schema = def.GetAttributeValue<string>("schemaname");
var value = def.GetAttributeValue<AliasedValue>("ev.value")?.Value?.ToString();
var defaultValue = def.GetAttributeValue<string>("defaultvalue").ToString();
environmentVariables[schema] = string.IsNullOrEmpty(value)
? defaultValue: value;
}
}
catch(Exception ex)
{
throw new Exception("Error fetching environment variables : " + ex.Message);
}
}Call the method at the start of your Execute function to initialize and load your environment variables and pass all the environment variable names you want to retrieve.
public void Execute(IServiceProvider serviceProvider)
{
GetEnvironmentVariables("sm_APIKey", "sm_APISecret");
// your plugin logic here
}You can then easily access any variable as follows:
environmentVariables["sm_APIKey"]By using this approach, your plugin dynamically retrieves environment-specific values without hardcoding them. Compared to secure or unsecure plugin configurations, environment variables provide better maintainability and flexibility, allowing you to manage shared settings consistently across Dataverse, Power Automate, and other solutions.