Is it possible to add fields definitions in entity? I created an entity using drupal console and now I would like to add fields to it. These should be references to other entities. I want these fields to be added programmatically, in the code. Ideally in the entity class so I can use entity methods to load referenced entities. How do I do that?

Thanks.
When you create an entity using Drupal Console you'll find such a field as example already defined in baseFieldDefinitions(), which references the user entity:

$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
  -&gt;setLabel(t('Authored by'))
  -&gt;setDescription(t('The user ID of author of the {{ label }} entity.'))
  -&gt;setRevisionable(TRUE)
  -&gt;setSetting('target_type', 'user')
  -&gt;setSetting('handler', 'default')
  -&gt;setTranslatable(TRUE)
  -&gt;setDisplayOptions('view', [
    'label' =&gt; 'hidden',
    'type' =&gt; 'author',
    'weight' =&gt; 0,
  ])
  -&gt;setDisplayOptions('form', [
    'type' =&gt; 'entity_reference_autocomplete',
    'weight' =&gt; 5,
    'settings' =&gt; [
      'match_operator' =&gt; 'CONTAINS',
      'size' =&gt; '60',
      'autocomplete_type' =&gt; 'tags',
      'placeholder' =&gt; '',
    ],
  ])
  -&gt;setDisplayConfigurable('form', TRUE)
  -&gt;setDisplayConfigurable('view', TRUE);


You can define as target other entities:

  -&gt;setSetting('target_type', 'my_other_entity')


BTW the two last two lines of the example make this base field configurable in UI. You can set this to FALSE if you don't want that anyone can change the configuration you've made in code.

You can customize this, for example if you want a dropdown select element:

  -&gt;setDisplayOptions('form', [
    'type' =&gt; 'options_select',
    'weight' =&gt; 5,
    'settings' =&gt; [
    ],


To implement code to load the referenced entities extend the field widget OptionsSelectWidget, add a custom plugin id to the annotations my_options_select, which you can use for the type in the example above

    'type' =&gt; 'my_options_select',


and override the plugin methods to load the options. For simple cases use hook_options_list_alter, this hook is invoked by the widget base class method getOptions().