Skip to content

_🛠️ Refactor suggestion_ #77

Description

@gitnasr

🛠️ Refactor suggestion

⚠️ Potential issue

ReverseMap risks creating half-populated Asset instances

The reverse mapping from PostAssetView → PostAsset implicitly tries to hydrate the nested Asset navigation property (Asset.Url).
Without an explicit ForPath configuration, AutoMapper will happily new-up an Asset with only Url set, leaving required columns such as Id, CreatedAt, etc. null.
That silent partial-entity creation is a common source of DbUpdateExceptions when EF Core later tries to persist the graph.

Consider either:

-CreateMap<PostAsset, PostAssetView>()
-    .ForMember(d => d.Id,  o => o.MapFrom(s => s.AssetId))
-    .ForMember(d => d.Url, o => o.MapFrom(s => s.Asset.Url))
-    .ReverseMap();
+// Domain → view only; write-back is handled by commands/DTOs dedicated to persisting PostAssets
+CreateMap<PostAsset, PostAssetView>()
+    .ForMember(d => d.Id,  o => o.MapFrom(s => s.AssetId))
+    .ForMember(d => d.Url, o => o.MapFrom(s => s.Asset.Url));

or, if two-way mapping is truly needed, make the reverse path explicit:

CreateMap<PostAsset, PostAssetView>()
    .ForMember(d => d.Id,  o => o.MapFrom(s => s.AssetId))
    .ForMember(d => d.Url, o => o.MapFrom(s => s.Asset.Url))
    .ReverseMap()
        .ForMember(d => d.AssetId,  o => o.MapFrom(s => s.Id))
        .ForPath(d => d.Asset.Url, o => o.MapFrom(s => s.Url));

Failing to tighten this up will surface only at runtime—often in production.

🤖 Prompt for AI Agents
In Dentizone.Application/AutoMapper/Posts/PostProfile.cs around lines 14 to 17,
the current ReverseMap configuration risks creating partially populated Asset
entities when mapping from PostAssetView to PostAsset, which can cause runtime
DbUpdateExceptions. To fix this, explicitly configure the reverse mapping by
adding ForMember for AssetId mapped from Id and ForPath for Asset.Url mapped
from Url, ensuring the nested Asset object is fully and correctly hydrated
during reverse mapping.

Originally posted by @coderabbitai[bot] in #75 (comment)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions