How to set a attribute as a Primary Key via script?

There is a entity and through script I am able to create a attribute and set its data type as BigInt.

I also have a key defined. I want to associate this attribute to that Key to make it a PK.

I believe that I need to first mark the attribute a Primary Key and then associate with the Key. Am I right? If so, how to mark a Attribute as a PK via script?



Hello Rajesh,

Try adding the following lines to your code:

Key = [EntityName].Keys.GetObject(0); // Every entity contains a Primary Key, even if it’s hidden. It is usually the first one in the array of Entity Keys.
Key.InVisible = false;

Basically you create a Key, set it as Primary and then associate the Attribute with the Key. Hopefully this will help you!


Thanks Lukas. It worked. Only thing is we have to use the Entity Object and Attribute object.

Oh yes, you’re right, mistake on my part, sorry!

Another thing I need some help with code snippet is to establish a 1 to many relationship between two entities via script. The entities have been defined and PK also defined.

A relationship is created like this:

var Relationship = Model.AddLinkObject(2004, [Entity1], [Entity2]);

TDM automatically created 1:N relationship between Entity 1 and Entity 2.

There are a few more options here. First, you can set mandatory parent or child by using these properties:

Relationship.MadatoryParent = true/false;
Relationship.MandatoryChild = true/false;

You also have the option to set the child entity cardinality like this:

Relationship.CardinalityChild = number
// 1 -> Child cardinality set to 1
// -1 -> Child cardinality set to Many

It worked. Thanks!


is there any way how to specify for the foreign key of the relationship an alllready existing field in the child entity?

After some more tries, I have found following solution, which works for me, because I have the one-field primary keys in every table, so it can be more simple:

var beforeNotNullAttr = FKField.NotNull; //situation NotNull before mapping

var Relationship = Model.AddLinkObject(2004, MasterEntity, ChildEntity);

Relationship.MandatoryParent = beforeNotNullAttr;

Relationship.Identifying = false;

// map the relationship to the correct existing

// field - this works only in the case of one and only PK id field in every entity,

// otherwise it must be much more complex process with multiple FK

// and PK fields involved:

var FK = Relationship.ForeignKeys.GetObject(0);

FK.SetAttributes(PKField, FKField); //SetAttributes

FK.ChangeChildAttribute(FKField); //mapping (attribute)

(FYI: FK Field and PKField have been obtained from the entity attributes by statements like

FKField = ChildEntity.Attributes.GetObject(k)

PKField = MasterEntity.Attributes.GetObject(j)