diff --git a/src/Mapster.Tests/WhenMappingToInterface.cs b/src/Mapster.Tests/WhenMappingToInterface.cs index 5e6f0358..00af2104 100644 --- a/src/Mapster.Tests/WhenMappingToInterface.cs +++ b/src/Mapster.Tests/WhenMappingToInterface.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; +using Newtonsoft.Json; namespace Mapster.Tests { @@ -266,6 +268,27 @@ public void MappingToInteraceWithReadonlyProps_AllPropsInitialized() ); } + [TestMethod] + public void MappingToInterface_VerifyReadonlyPropsInterfaceRule() + { + SampleInterfaceCls source = new SampleInterfaceCls + { + ActivityData = new SampleActivityData + { + Data = new SampleActivityParsedData + { + Steps = new List { "A", "B", "C" } + } + } + }; + + SampleInterfaceCls target = source.Adapt(); + target.ShouldNotBeNull(); + target.ShouldSatisfyAllConditions( + () => target.ActivityData.ShouldBe(source.ActivityData) + ); + } + public interface IInheritedDtoWithoutProperties : IInheritedDto { } @@ -374,6 +397,42 @@ public class PropertyInitializationTestSource public int Property1 { get; set; } public int Property2 { get; set; } } + + public interface IActivityData + { + + } + + public class SampleInterfaceCls + { + [Newtonsoft.Json.JsonIgnore] + public IActivityData? ActivityData { get; set; } + + public SampleInterfaceCls() + { + + } + + public SampleInterfaceCls(IActivityData data) + { + SetActivityData(data); + } + + public void SetActivityData(IActivityData data) + { + ActivityData = data; + } + } + + public class SampleActivityData : IActivityData + { + public SampleActivityParsedData Data { get; set; } + } + + public class SampleActivityParsedData + { + public List Steps { get; set; } = new List(); + } } } diff --git a/src/Mapster/Adapters/ReadOnlyInterfaceAdapter.cs b/src/Mapster/Adapters/ReadOnlyInterfaceAdapter.cs index df4a0f66..fbd5a78b 100644 --- a/src/Mapster/Adapters/ReadOnlyInterfaceAdapter.cs +++ b/src/Mapster/Adapters/ReadOnlyInterfaceAdapter.cs @@ -10,7 +10,7 @@ internal class ReadOnlyInterfaceAdapter : ClassAdapter protected override bool CanMap(PreCompileArgument arg) { - return arg.DestinationType.IsInterface; + return arg.DestinationType.IsInterface && arg.DestinationType.GetProperties().Length > 0; } protected override bool CanInline(Expression source, Expression? destination, CompileArgument arg)