diff --git a/CatFactory.Tests/RecordDefinitionTests.cs b/CatFactory.Tests/RecordDefinitionTests.cs index 7b67a9d..f9ca298 100644 --- a/CatFactory.Tests/RecordDefinitionTests.cs +++ b/CatFactory.Tests/RecordDefinitionTests.cs @@ -1,4 +1,5 @@ -using CatFactory.ObjectOrientedProgramming; +using System; +using CatFactory.ObjectOrientedProgramming; using Xunit; namespace CatFactory.Tests @@ -91,5 +92,26 @@ public void TestConvertClassToRecordWithConvertOptions() Assert.True(recordDefinition.Fields.Count == classDefinition.Fields.Count); Assert.True(recordDefinition.Properties.Count == classDefinition.Properties.Count); } + + [Fact] + public void Test_RefactRecordDefinitionFromAnonymous() + { + // Arrange + var anonymousDefinition = new + { + Id = Guid.Empty, + Name = "", + Price = 0m, + ReleaseDate = DateTime.Now + }; + + // Act + var recordDefinition = anonymousDefinition.RefactRecordDefinition("StockItem"); + + // Assert + Assert.True(string.IsNullOrEmpty(recordDefinition.Namespace)); + Assert.True(recordDefinition.Name == "StockItem"); + Assert.True(recordDefinition.Properties.Count == 4); + } } } diff --git a/CatFactory/CatFactory.csproj b/CatFactory/CatFactory.csproj index e116659..6a27f43 100644 --- a/CatFactory/CatFactory.csproj +++ b/CatFactory/CatFactory.csproj @@ -22,6 +22,7 @@ Fix issue 32: https://github.com/hherzl/CatFactory/issues/32 Fix issue 33: https://github.com/hherzl/CatFactory/issues/33 Fix issue 34: https://github.com/hherzl/CatFactory/issues/34 + Fix issue 35: https://github.com/hherzl/CatFactory/issues/35 https://github.com/hherzl/CatFactory/blob/master/LICENSE diff --git a/CatFactory/ObjectOrientedProgramming/ObjectExtensions.cs b/CatFactory/ObjectOrientedProgramming/ObjectExtensions.cs index 82c527b..540e504 100644 --- a/CatFactory/ObjectOrientedProgramming/ObjectExtensions.cs +++ b/CatFactory/ObjectOrientedProgramming/ObjectExtensions.cs @@ -33,5 +33,32 @@ public static ClassDefinition RefactClassDefinition(this object obj, string name return classDefinition; } + + /// + /// Creates a new from instance + /// + /// Instance of model + /// Name of + /// Namespace of + /// + public static RecordDefinition RefactRecordDefinition(this object obj, string name = null, string ns = null) + { + var sourceType = obj.GetType(); + + var recordDefinition = new RecordDefinition + { + Name = string.IsNullOrEmpty(name) ? sourceType.Name : name, + Namespace = string.IsNullOrEmpty(ns) ? string.Empty : ns + }; + + foreach (var property in sourceType.GetProperties().Where(item => item.CanRead)) + { + var type = property.PropertyType.Name; + + recordDefinition.AddAutomaticProperty(AccessModifier.Public, type, property.Name); + } + + return recordDefinition; + } } }