Structural transitions are invariably affected by lattice distortions. If the body is to remain crackfree, the strain field cannot be arbitrary but has to satisfy the Saint-Venant compatibility constraint. Equivalently, an incompatibility constraint consistent with the actual dislocation network has to be satisfied in media with dislocations. This constraint can be incorporated into strain-based free energy functionals to study the influence of dislocations on phase stability. We provide a systematic analysis of this constraint in 3D and show how three incompatibility equations accommodate an arbitrary dislocation density. This approach allows the internal stress field to be calculated for an anisotropic material with spatially inhomogeneous microstructure and distribution of dislocations by minimizing the free energy. This is illustrated by calculating the stress field of an edge dislocation and comparing it with that of an edge dislocation in an infinite isotropic medium. We outline how this procedure can be utilized to study the interaction of plasticity with polarization and magnetization.