From 9c4d07b3b2acd55cd2089378ffb04ac4ca7bee71 Mon Sep 17 00:00:00 2001 From: Vdevers Date: Tue, 29 Sep 2026 12:30:44 -0400 Subject: [PATCH] Take the named-member overloads a migration writes ForMember by name, MapFrom by name, ForAllMembers, and ForSourceMember with DoNotValidate. They exist because the library this one is a drop-in for has them and a configuration that chooses a member somewhere a lambda cannot reach had to be rewritten by hand. All four were run side by side against AutoMapper and answer the same. A dotted name walks a path, the shape the expression overloads already took, and it is resolved while the configuration is built rather than when a map runs: a misspelling is a configuration error instead of a member that quietly maps to nothing. The expression overloads stay the ones to prefer, since they keep the compiler involved, and the documentation says so. The analyser learned the string form as well, so a member named as text is still tracked by the checks that say two calls disagree about it. The rest of the surface comparison is deliberately not here. Copying the overload list wholesale would break source compatibility: over there the extra PreCondition overloads make o.PreCondition(s => false) ambiguous, and that call compiles here today. --- CHANGELOG.md | 15 ++ .../ConfigurationAnalyzer.cs | 13 ++ .../Configuration/IMappingExpression.cs | 49 ++++++ .../IMemberConfigurationExpression.cs | 15 ++ .../ISourceMemberConfigurationExpression.cs | 19 +++ .../Configuration/MemberConfiguration.cs | 10 ++ .../Configuration/MemberNameResolver.cs | 83 ++++++++++ .../SourceMemberConfiguration.cs | 12 ++ .../Configuration/TypeMapConfiguration.cs | 91 +++++++++++ src/Mapperion/Model/TypeMapDefinition.cs | 8 + src/Mapperion/PublicAPI.Unshipped.txt | 8 + .../Validation/ConfigurationValidator.cs | 5 + .../Configuration/NamedMemberTests.cs | 152 ++++++++++++++++++ 13 files changed, 480 insertions(+) create mode 100644 src/Mapperion/Configuration/ISourceMemberConfigurationExpression.cs create mode 100644 src/Mapperion/Configuration/MemberNameResolver.cs create mode 100644 src/Mapperion/Configuration/SourceMemberConfiguration.cs create mode 100644 tests/Mapperion.Tests/Configuration/NamedMemberTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 73b00c7..6b47ba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ Before v1.0, a minor version may introduce breaking changes. ## [Unreleased] +### Added + +- **The four members a migration from AutoMapper actually writes.** `ForMember` taking the + destination member as text, `MapFrom` taking the source member as text, `ForAllMembers`, and + `ForSourceMember` with the one thing there is to say about a source member — `DoNotValidate()`, + which excuses it from validation against the source list. All four were run side by side against + AutoMapper and answer the same. +- A dotted name walks a path, the shape the expression overloads already accepted, and the name is + resolved while the configuration is built: a misspelling is a configuration error rather than a + member that quietly maps to nothing. The expression overloads are still the ones to prefer, + since they keep the compiler involved. +- The rest of the surface comparison was left alone on purpose. Copying AutoMapper's overload list + wholesale would break source compatibility here: its extra `PreCondition` overloads make + `o.PreCondition(s => false)` ambiguous, and that call compiles today. + ### Fixed - **`ForPath` now owns the member its path starts at.** It only owned the one the path ends at, diff --git a/src/Mapperion.Analyzers/ConfigurationAnalyzer.cs b/src/Mapperion.Analyzers/ConfigurationAnalyzer.cs index 49f9bf7..a87c047 100644 --- a/src/Mapperion.Analyzers/ConfigurationAnalyzer.cs +++ b/src/Mapperion.Analyzers/ConfigurationAnalyzer.cs @@ -321,8 +321,21 @@ private static bool IsScope( /// The destination member a lambda points at, as it is written, so that /// d => d.Customer.Name becomes Customer.Name. /// + /// + /// A member is selected either by an expression or, since the overloads that take one as + /// text exist, by a literal string. A name built at run time cannot be read here, and a + /// member this returns null for is simply not tracked — the diagnostics below say that two + /// calls disagree, so saying nothing is the right answer when one of them is unknowable. + /// private static string? Path(ExpressionSyntax expression) { + if (expression is LiteralExpressionSyntax literal && + literal.IsKind(SyntaxKind.StringLiteralExpression)) + { + string text = literal.Token.ValueText; + return text.Length == 0 ? null : text; + } + if (expression is not LambdaExpressionSyntax lambda || lambda.Body is not ExpressionSyntax body) { return null; diff --git a/src/Mapperion/Configuration/IMappingExpression.cs b/src/Mapperion/Configuration/IMappingExpression.cs index 8dedf8a..b875bbb 100644 --- a/src/Mapperion/Configuration/IMappingExpression.cs +++ b/src/Mapperion/Configuration/IMappingExpression.cs @@ -51,6 +51,55 @@ IMappingExpression ForPath( Expression> destinationPath, Action> pathOptions); + /// + /// Configures one destination member, named as text rather than selected by an expression. + /// + /// + /// For a member chosen somewhere a lambda cannot reach — a settings file, a table of + /// overrides, a loop. It costs the compiler's checking, so the expression overload is the + /// one to reach for when there is a choice. A dotted name walks a path, exactly as + /// does. + /// + /// The member name, or a dotted path to one. + /// The configuration applied to that member. + /// This expression, for chaining. + /// Either argument is . + /// + /// The destination has no member of that name. + /// + IMappingExpression ForMember( + string destinationMember, + Action> memberOptions); + + /// + /// Applies the same configuration to every destination member. + /// + /// + /// Every writable member of the destination, including the ones no call has mentioned. + /// It runs before the conventions fill anything in, so a member it ignores stays ignored + /// and a member it gives a source to keeps that source. + /// + /// The configuration applied to each member. + /// This expression, for chaining. + /// is . + IMappingExpression ForAllMembers( + Action> memberOptions); + + /// + /// Configures one member of the source. + /// + /// + /// There is one thing to say about a source member, and it only means anything under + /// : that it is allowed to go unread. + /// + /// A member access on the source. + /// The configuration applied to that member. + /// This expression, for chaining. + /// Either argument is . + IMappingExpression ForSourceMember( + Expression> sourceMember, + Action memberOptions); + /// /// Configures one parameter of the destination constructor. Parameter names are matched /// ignoring case, because C# names parameters in camelCase and properties in PascalCase. diff --git a/src/Mapperion/Configuration/IMemberConfigurationExpression.cs b/src/Mapperion/Configuration/IMemberConfigurationExpression.cs index 7aa524a..fc5149d 100644 --- a/src/Mapperion/Configuration/IMemberConfigurationExpression.cs +++ b/src/Mapperion/Configuration/IMemberConfigurationExpression.cs @@ -20,6 +20,21 @@ public interface IMemberConfigurationExpression /// The expression that reads the value. void MapFrom(Expression> sourceMember); + /// + /// Takes the value from the source member of the given name, or from the dotted path to + /// one. + /// + /// + /// The name is resolved while the configuration is built, so a misspelling is a + /// configuration error and not a member that quietly maps to nothing. + /// + /// The source member name, or a dotted path to one. + /// is . + /// + /// The source has no member of that name. + /// + void MapFrom(string sourceMember); + /// /// Takes the value from a resolver, which sees the whole source and destination. /// diff --git a/src/Mapperion/Configuration/ISourceMemberConfigurationExpression.cs b/src/Mapperion/Configuration/ISourceMemberConfigurationExpression.cs new file mode 100644 index 0000000..fd418e9 --- /dev/null +++ b/src/Mapperion/Configuration/ISourceMemberConfigurationExpression.cs @@ -0,0 +1,19 @@ +namespace Mapperion +{ + /// + /// What can be said about a member of the source. + /// + /// + /// There is one thing, and it only means anything under + /// : validation against the source list reports + /// every readable member that no destination member reads, and this excuses one of them. + /// + public interface ISourceMemberConfigurationExpression + { + /// + /// Leaves this source member out of validation, so it may go unread without being + /// reported. + /// + void DoNotValidate(); + } +} diff --git a/src/Mapperion/Configuration/MemberConfiguration.cs b/src/Mapperion/Configuration/MemberConfiguration.cs index 44b3b5c..94d2226 100644 --- a/src/Mapperion/Configuration/MemberConfiguration.cs +++ b/src/Mapperion/Configuration/MemberConfiguration.cs @@ -61,6 +61,16 @@ public void MapFrom() isIgnored = false; } + public void MapFrom(string sourceMember) + { + Guard.NotNull(sourceMember, nameof(sourceMember)); + + source = new MemberPathSource( + MemberNameResolver.Path(typeof(TSource), sourceMember, "source")); + + isIgnored = false; + } + public void ConvertUsing() where TValueConverter : IValueConverter { diff --git a/src/Mapperion/Configuration/MemberNameResolver.cs b/src/Mapperion/Configuration/MemberNameResolver.cs new file mode 100644 index 0000000..f9c08ad --- /dev/null +++ b/src/Mapperion/Configuration/MemberNameResolver.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Mapperion.Internal; +using Mapperion.Model; + +namespace Mapperion.Configuration +{ + /// + /// Finds a member from its name, for the overloads that take one as text. + /// + /// + /// + /// A name is what you have when the member is chosen somewhere a lambda cannot reach — a + /// configuration file, a table of overrides, a loop over names. It costs the compiler's + /// checking, which is why the expression overloads exist and are the ones to prefer. + /// + /// + /// A dotted name is a path, the same shape the expression overloads accept: Customer.Name + /// walks two steps. The name is resolved here, while the configuration is being built, so a + /// misspelling is a configuration error rather than a member that silently maps to nothing. + /// + /// + internal static class MemberNameResolver + { + private const BindingFlags Lookup = + BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; + + internal static MemberPath Path(Type type, string name, string role) + { + Guard.NotNull(type, nameof(type)); + + if (string.IsNullOrWhiteSpace(name)) + { + throw new MapperConfigurationException("A " + role + " member name cannot be empty."); + } + + string[] steps = name!.Split('.'); + var descriptors = new List(steps.Length); + Type current = type; + + foreach (string step in steps) + { + MemberDescriptor descriptor = Step(current, step.Trim(), name!, role); + descriptors.Add(descriptor); + current = descriptor.MemberType; + } + + return new MemberPath(descriptors); + } + + [UnconditionalSuppressMessage("Trimming", "IL2070", Justification = + "Members are looked up by name here, which the trimmer cannot follow. The fluent configuration is only reachable through MapperConfiguration, which already says so.")] + private static MemberDescriptor Step(Type type, string step, string whole, string role) + { + PropertyInfo? property = type.GetProperty(step, Lookup); + + if (property is not null) + { + return MemberDescriptor.ForProperty(property); + } + + FieldInfo? field = type.GetField(step, Lookup); + + if (field is not null) + { + return MemberDescriptor.ForField(field); + } + + MethodInfo? method = type.GetMethod(step, Lookup, null, Type.EmptyTypes, null); + + if (method is not null && method.ReturnType != typeof(void)) + { + return MemberDescriptor.ForMethod(method); + } + + throw new MapperConfigurationException( + "'" + type.Name + "' has no " + role + " member called '" + step + "'" + + (whole == step ? "." : ", named as part of '" + whole + "'.")); + } + } +} diff --git a/src/Mapperion/Configuration/SourceMemberConfiguration.cs b/src/Mapperion/Configuration/SourceMemberConfiguration.cs new file mode 100644 index 0000000..3bb8803 --- /dev/null +++ b/src/Mapperion/Configuration/SourceMemberConfiguration.cs @@ -0,0 +1,12 @@ +namespace Mapperion.Configuration +{ + /// + /// What ForSourceMember collects. One flag, because there is one thing to say. + /// + internal sealed class SourceMemberConfiguration : ISourceMemberConfigurationExpression + { + internal bool IsExcludedFromValidation { get; private set; } + + public void DoNotValidate() => IsExcludedFromValidation = true; + } +} diff --git a/src/Mapperion/Configuration/TypeMapConfiguration.cs b/src/Mapperion/Configuration/TypeMapConfiguration.cs index 27d449d..1472320 100644 --- a/src/Mapperion/Configuration/TypeMapConfiguration.cs +++ b/src/Mapperion/Configuration/TypeMapConfiguration.cs @@ -39,6 +39,7 @@ internal sealed class TypeMapConfiguration private readonly List derivedMaps = new List(); private readonly List baseMaps = new List(); private readonly List includedMembers = new List(); + private readonly List unvalidatedSourceMembers = new List(); private readonly List beforeMapActions = new List(); private readonly List afterMapActions = new List(); private int? maxDepth; @@ -87,6 +88,64 @@ public IMappingExpression ForPath( return this; } + public IMappingExpression ForMember( + string destinationMember, + Action> memberOptions) + { + Guard.NotNull(destinationMember, nameof(destinationMember)); + Guard.NotNull(memberOptions, nameof(memberOptions)); + + MemberPath path = MemberNameResolver.Path( + typeof(TDestination), destinationMember, "destination"); + + // A single step is a member and not a path, which is the same rule ForPath follows. + MemberConfiguration configuration = path.IsFlattened + ? FindOrAddPath(path) + : FindOrAdd(path.Leaf); + + memberOptions(configuration); + return this; + } + + /// + /// Every writable member of the destination, whether or not a call has already mentioned + /// it, and the ones already mentioned keep what they were given first — the action is + /// applied on top. It runs here rather than at build time so that the conventions see the + /// result and leave those members alone. + /// + public IMappingExpression ForAllMembers( + Action> memberOptions) + { + Guard.NotNull(memberOptions, nameof(memberOptions)); + + foreach (MemberDescriptor destination in DestinationMembers()) + { + memberOptions(FindOrAdd(destination)); + } + + return this; + } + + public IMappingExpression ForSourceMember( + Expression> sourceMember, + Action memberOptions) + { + Guard.NotNull(sourceMember, nameof(sourceMember)); + Guard.NotNull(memberOptions, nameof(memberOptions)); + + MemberPath path = MemberExpressionParser.ParseIncludedMember(sourceMember); + var configuration = new SourceMemberConfiguration(); + + memberOptions(configuration); + + if (configuration.IsExcludedFromValidation) + { + unvalidatedSourceMembers.Add(path.Steps[0]); + } + + return this; + } + public IMappingExpression IncludeMembers( params Expression>[] members) { @@ -285,9 +344,41 @@ public TypeMapDefinition Build(MapperOptions options) AfterMapActions = afterMapActions.ToArray(), MaxDepth = maxDepth, PreserveReferences = preserveReferences, + UnvalidatedSourceMembers = unvalidatedSourceMembers.ToArray(), }; } + /// + /// Every writable member of the destination, found the plain way. ForAllMembers is the + /// only caller and it runs while the configuration is being written, before the options + /// that drive the real member walk are known. + /// + [UnconditionalSuppressMessage("Trimming", "IL2090", Justification = + "Members are looked up by name here, which the trimmer cannot follow. The fluent configuration is only reachable through MapperConfiguration, which already says so.")] + private static IEnumerable DestinationMembers() + { + const System.Reflection.BindingFlags lookup = + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.FlattenHierarchy; + + foreach (System.Reflection.PropertyInfo property in typeof(TDestination).GetProperties(lookup)) + { + if (property.CanWrite && property.GetIndexParameters().Length == 0) + { + yield return MemberDescriptor.ForProperty(property); + } + } + + foreach (System.Reflection.FieldInfo field in typeof(TDestination).GetFields(lookup)) + { + if (!field.IsInitOnly) + { + yield return MemberDescriptor.ForField(field); + } + } + } + private CtorParamConfiguration FindOrAddParameter(string name) { for (int i = 0; i < constructorParameters.Count; i++) diff --git a/src/Mapperion/Model/TypeMapDefinition.cs b/src/Mapperion/Model/TypeMapDefinition.cs index 6ca2b85..223c606 100644 --- a/src/Mapperion/Model/TypeMapDefinition.cs +++ b/src/Mapperion/Model/TypeMapDefinition.cs @@ -69,6 +69,13 @@ public TypeMapDefinition(TypeMapKey key) /// Gets which side must be fully covered for this map to validate. public MemberListValidation MemberListValidation { get; init; } = MemberListValidation.Destination; + /// + /// Source members that ForSourceMember(..., o => o.DoNotValidate()) excused from + /// validation against the source list. + /// + public IReadOnlyList UnvalidatedSourceMembers { get; init; } = + System.Array.Empty(); + /// Gets the maps for derived type pairs handled polymorphically by this one. public IReadOnlyList DerivedMaps { get; init; } = NoKeys; @@ -126,6 +133,7 @@ internal TypeMapDefinition WithResolved( MaxDepth = MaxDepth, PreserveReferences = PreserveReferences, MemberListValidation = MemberListValidation, + UnvalidatedSourceMembers = UnvalidatedSourceMembers, DerivedMaps = DerivedMaps, BaseMaps = BaseMaps, IncludedMembers = IncludedMembers, diff --git a/src/Mapperion/PublicAPI.Unshipped.txt b/src/Mapperion/PublicAPI.Unshipped.txt index 7dc5c58..7c01987 100644 --- a/src/Mapperion/PublicAPI.Unshipped.txt +++ b/src/Mapperion/PublicAPI.Unshipped.txt @@ -1 +1,9 @@ #nullable enable +Mapperion.IMappingExpression.ForAllMembers(System.Action!>! memberOptions) -> Mapperion.IMappingExpression! +Mapperion.IMappingExpression.ForMember(string! destinationMember, System.Action!>! memberOptions) -> Mapperion.IMappingExpression! +Mapperion.IMappingExpression.ForSourceMember(System.Linq.Expressions.Expression!>! sourceMember, System.Action! memberOptions) -> Mapperion.IMappingExpression! +Mapperion.IMemberConfigurationExpression.MapFrom(string! sourceMember) -> void +Mapperion.ISourceMemberConfigurationExpression +Mapperion.ISourceMemberConfigurationExpression.DoNotValidate() -> void +Mapperion.Model.TypeMapDefinition.UnvalidatedSourceMembers.get -> System.Collections.Generic.IReadOnlyList! +Mapperion.Model.TypeMapDefinition.UnvalidatedSourceMembers.init -> void diff --git a/src/Mapperion/Validation/ConfigurationValidator.cs b/src/Mapperion/Validation/ConfigurationValidator.cs index e0429f0..82c2a54 100644 --- a/src/Mapperion/Validation/ConfigurationValidator.cs +++ b/src/Mapperion/Validation/ConfigurationValidator.cs @@ -305,6 +305,11 @@ private static void ValidateSource(TypeMapDefinition map, TypeMembers members, L } } + foreach (MemberDescriptor excused in map.UnvalidatedSourceMembers) + { + consumed.Add(excused); + } + foreach (MemberDescriptor candidate in members.Readable(map.SourceType)) { if (!consumed.Contains(candidate)) diff --git a/tests/Mapperion.Tests/Configuration/NamedMemberTests.cs b/tests/Mapperion.Tests/Configuration/NamedMemberTests.cs new file mode 100644 index 0000000..c2cfac7 --- /dev/null +++ b/tests/Mapperion.Tests/Configuration/NamedMemberTests.cs @@ -0,0 +1,152 @@ +using System; +using Shouldly; +using Xunit; + +namespace Mapperion.Tests.Configuration +{ + public sealed class Ledger + { + public string Owner { get; set; } = string.Empty; + + public int Balance { get; set; } + + public Office Office { get; set; } = new Office(); + + public string Unread { get; set; } = string.Empty; + } + + public sealed class Office + { + public string Code { get; set; } = string.Empty; + } + + public sealed class LedgerDto + { + public string Owner { get; set; } = string.Empty; + + public int Balance { get; set; } + + public string OfficeCode { get; set; } = string.Empty; + } + + /// + /// The overloads that name a member as text, and the one that speaks about the source. They + /// exist because the library this one is a drop-in for has them, and a configuration that + /// chooses a member somewhere a lambda cannot reach had to be rewritten by hand without them. + /// + public sealed class NamedMemberTests + { + [Fact] + public void ForMember_takes_the_destination_member_by_name() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ForMember("Owner", o => o.MapFrom(s => s.Owner.ToUpperInvariant()))); + + LedgerDto result = config.CreateMapper() + .Map(new Ledger { Owner = "ada" }); + + result.Owner.ShouldBe("ADA"); + } + + [Fact] + public void MapFrom_takes_the_source_member_by_name() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ForMember(d => d.Owner, o => o.MapFrom("Unread"))); + + LedgerDto result = config.CreateMapper() + .Map(new Ledger { Owner = "ada", Unread = "borrowed" }); + + result.Owner.ShouldBe("borrowed"); + } + + /// A dotted name walks a path, the same shape the expression overloads accept. + [Fact] + public void A_dotted_name_walks_a_path() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ForMember("OfficeCode", o => o.MapFrom("Office.Code"))); + + LedgerDto result = config.CreateMapper() + .Map(new Ledger { Office = new Office { Code = "B7" } }); + + result.OfficeCode.ShouldBe("B7"); + } + + /// + /// The name is resolved while the configuration is built, so a misspelling is a + /// configuration error rather than a member that quietly maps to nothing. That is the + /// whole reason to prefer the expression overloads where there is a choice. + /// + [Fact] + public void A_name_that_matches_nothing_is_a_configuration_error() + { + MapperConfigurationException error = Should.Throw( + () => new MapperConfiguration(cfg => cfg + .CreateMap() + .ForMember("Nonexistent", o => o.Ignore()))); + + error.Message.ShouldContain("Nonexistent"); + } + + [Fact] + public void A_source_name_that_matches_nothing_is_a_configuration_error() + { + MapperConfigurationException error = Should.Throw( + () => new MapperConfiguration(cfg => cfg + .CreateMap() + .ForMember(d => d.Owner, o => o.MapFrom("Nonexistent")))); + + error.Message.ShouldContain("Nonexistent"); + } + + [Fact] + public void ForAllMembers_reaches_every_destination_member() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ForAllMembers(o => o.Ignore())); + + LedgerDto result = config.CreateMapper() + .Map(new Ledger { Owner = "ada", Balance = 5 }); + + result.Owner.ShouldBe(string.Empty); + result.Balance.ShouldBe(0); + result.OfficeCode.ShouldBe(string.Empty); + } + + /// + /// Validation against the source list reports every readable member no destination member + /// reads. This is how one of them is excused, and it is the only thing there is to say + /// about a source member. + /// + [Fact] + public void ForSourceMember_excuses_a_member_from_source_validation() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ValidateMemberList(Mapperion.Model.MemberListValidation.Source) + .ForMember(d => d.OfficeCode, o => o.MapFrom(s => s.Office.Code)) + .ForSourceMember(s => s.Unread, o => o.DoNotValidate())); + + Should.NotThrow(() => config.AssertConfigurationIsValid()); + } + + [Fact] + public void An_unread_source_member_is_still_reported_without_it() + { + var config = new MapperConfiguration(cfg => cfg + .CreateMap() + .ValidateMemberList(Mapperion.Model.MemberListValidation.Source) + .ForMember(d => d.OfficeCode, o => o.MapFrom(s => s.Office.Code))); + + MapperConfigurationException error = + Should.Throw(() => config.AssertConfigurationIsValid()); + + error.Message.ShouldContain("Unread"); + } + } +}