How to define primary keys on multiple attributes?

0
Hi,   In traditional development environments it's possible to define primary keys on entity level, where the primary key is the combination of multiple attributes. It looks like Mendix does not support this at all, which is odd, as underlying databases like SQL do. I tried to use Unique via validation rules, but it can only be set on 1 attribute, not on a combination of attributes.   What is the best way to define primary keys in the domain model, in order to avoid duplicate records?  
asked
3 answers
2

The best way to define primary keys in the domain model, in order to avoid duplicate records, is to not define Primary Keys at all as attributes. You have to make sure that you do this check in an object oriented way. So by trying to retrieve an object from your database that has the same data based on an Xpath. If you have found the object then you know that the object already exists in your database.

second, I wouldn't capture it in your domain model but in my logic. Make sure that you have the correct logic in your save buttons (microflows) with which you can immediately check whether you are creating an object that does not yet exist. You can even do this during creation by means of validations that arise from an on-change microflow.

answered
2

Mendix objects always have a primary key attribute called ID. The value of this attribute is generated by mendix. You cannot define another attribute as the key.

You can however, define other attributes to be unique, so you can find the object you are looking for by comparing it with another attribute.

Unique constraints on mendix entities are enforced in the database, by creating a unique constraint on the database table. This ensures the attribute will always be unique, regardless how many concurrent sessions you have at the same time. Handling unique validations in microflows can’t guarantee uniqueness, as you might have multiple microflows doing the same check at the same time. Uniqueness needs to be validated in the database.

Uniqueness constraints in mendix are limited to a single attribute. The best way to ensure uniqueness on multiple attributes is to concatenate the values of the different attributes in an additional atrribute, and create a unique constraint on that attribute.

answered
1

If it must be validated in all cases at database level, add a validation microflow in a before commit event

answered