Fix DynDto

This commit is contained in:
Stone_Red
2024-03-18 18:05:27 +01:00
parent 09512ef6db
commit 5269a8d56d
2 changed files with 14 additions and 11 deletions
@@ -5,10 +5,10 @@ using System.Dynamic;
namespace CuteUtils.Tests; namespace CuteUtils.Tests;
[TestClass] [TestClass]
public class UnitTest1 public class DynDtoTests
{ {
[TestMethod] [TestMethod]
public void TestMethod1() public void Convert_ToDto_ReturnsExpandoObject()
{ {
TestModel testModel = new() TestModel testModel = new()
{ {
@@ -27,7 +27,7 @@ public class UnitTest1
} }
[TestMethod] [TestMethod]
public void TestMethod2() public void Convert_ToDto_ReturnsGeneric()
{ {
TestModel testModel = new() TestModel testModel = new()
{ {
@@ -40,9 +40,9 @@ public class UnitTest1
Assert.IsNotNull(dto); Assert.IsNotNull(dto);
Assert.IsTrue(dto.Id != 0); Assert.IsTrue(dto.Id == 0);
Assert.IsTrue(dto.Name is not null); Assert.IsTrue(!string.IsNullOrWhiteSpace(dto.Name));
Assert.IsTrue(dto.Value is not null); Assert.IsTrue(dto.Value is not (0, ""));
} }
private class TestModel private class TestModel
@@ -52,14 +52,14 @@ public class UnitTest1
[DynDtoName(nameof(Name))] [DynDtoName(nameof(Name))]
public required string Name { get; set; } public required string Name { get; set; }
//[DynDtoName(nameof(Value))] [DynDtoName(nameof(Value))]
public required object Value { get; set; } public required object Value { get; set; }
} }
private class TestDto private class TestDto
{ {
public int Id { get; set; } = 0; public int Id { get; init; } = 0;
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public object Value { get; set; } = (15, "test"); public object Value { get; init; } = (0, string.Empty);
} }
} }
+5 -2
View File
@@ -2,6 +2,7 @@
using System.Reflection; using System.Reflection;
namespace CuteUtils.Reflection; namespace CuteUtils.Reflection;
public static class DynDto public static class DynDto
{ {
public static ExpandoObject ToDto(this object data) public static ExpandoObject ToDto(this object data)
@@ -25,8 +26,10 @@ public static class DynDto
public static T ToDto<T>(this object data, T dto) public static T ToDto<T>(this object data, T dto)
{ {
ArgumentNullException.ThrowIfNull(dto);
PropertyInfo[] dataProperties = data.GetType().GetProperties(); PropertyInfo[] dataProperties = data.GetType().GetProperties();
PropertyInfo[] dtoProperties = data.GetType().GetProperties(); PropertyInfo[] dtoProperties = dto.GetType().GetProperties();
foreach (PropertyInfo dataProperty in dataProperties) foreach (PropertyInfo dataProperty in dataProperties)
{ {
@@ -102,4 +105,4 @@ public static class DynDto
{ {
return FromDto(dto, new T()); return FromDto(dto, new T());
} }
} }