Reputation: 1
I am working on a large-scale project where I need to build multiple Power BI semantic models. Each model contains dozens of tables with multiple fields, and I need to establish relationships between these tables. Manually creating relationships for each model is time-consuming, so I am trying to automate this process using Tabular Editor and a JSON file.
For context:
Here is an example of the JSON file:
[
{
"FromTable": "ORDERS",
"FromColumn": "CustomerID",
"ToTable": "CUSTOMERS",
"ToColumn": "CustomerID",
"Cardinality": "ManyToOne",
"CrossFilteringBehavior": "BothDirections"
},
{
"FromTable": "ORDERS",
"FromColumn": "ProductID",
"ToTable": "PRODUCTS",
"ToColumn": "ProductID",
"Cardinality": "ManyToOne",
"CrossFilteringBehavior": "OneDirection"
}
]
I attempted to write a C# script in Tabular Editor to:
Here is the script I tried:
using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
string jsonFilePath = @"C:\path\to\relationship.json";
string jsonContent = File.ReadAllText(jsonFilePath);
var relationships = JsonConvert.DeserializeObject<List<Relationship>>(jsonContent);
public class Relationship
{
public string FromTable { get; set; }
public string FromColumn { get; set; }
public string ToTable { get; set; }
public string ToColumn { get; set; }
public string Cardinality { get; set; }
public string CrossFilteringBehavior { get; set; }
}
foreach (var rel in relationships)
{
var fromTable = Model.Tables[rel.FromTable];
var toTable = Model.Tables[rel.ToTable];
if (fromTable == null || toTable == null)
{
Output.WriteLine($"Table '{rel.FromTable}' or '{rel.ToTable}' does not exist in the model.");
continue;
}
var fromColumn = fromTable.Columns[rel.FromColumn];
var toColumn = toTable.Columns[rel.ToColumn];
if (fromColumn == null || toColumn == null)
{
Output.WriteLine($"Column '{rel.FromColumn}' or '{rel.ToColumn}' does not exist.");
continue;
}
var relationship = Model.Relationships.Add(fromColumn, toColumn);
relationship.Cardinality = rel.Cardinality == "ManyToOne" ? RelationshipCardinality.ManyToOne : RelationshipCardinality.OneToOne;
relationship.CrossFilteringBehavior = rel.CrossFilteringBehavior == "BothDirections" ? SecurityFilteringBehavior.BothDirections : SecurityFilteringBehavior.OneDirection;
Output.WriteLine($"Created relationship: {rel.FromTable}.{rel.FromColumn} -> {rel.ToTable}.{rel.ToColumn}");
}
However, the script does not seem to work as expected. Relationships are either not created, or the script is failing with many errors.
Any help or working script examples would be greatly appreciated!
Upvotes: 0
Views: 75