I have applied a default pricebook to a set of users. When I try to add products to that opportunity the pricebook already shows that it is selected at the product selection screen but still pricebook2Id remains blank at the opportunity level. Due to which when my code tries to insert another product from the backend(for some other functionality) it throws the following error
(caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId, unknown (versions 3.0 and higher must specify pricebook entry id, others must specify product id): [PricebookEntryId, unknown]).
On debugging I got to know that when PricebookEntryId is being assigned to the newly created product a check is happening for matching the (to be assigned) pricebookId with the pricebook2id present in the opportunity level which is null. So my code is not running in that part and throwing this error.