使用隐式/显式转换运算符是否违反单一职责模式而支持 DRY?

2024-01-11

我需要在这两个类之间进行转换,并且想要保持 DRY 但不违反单一职责模式......

public class Person
{
    public string Name {get;set;}
    public int ID {get;set;}
}

public class PersonEntity : TableServiceEntity
{
    public string Name {get;set;}
    public int ID {get;set;}

    // Code to set PartitionKey
    // Code to set RowKey
}

更多信息

我的 ASP.NET MVC 应用程序中有一些 Model 对象。由于我使用 Azure 存储,因此经常需要在 ViewModel 对象和 AzureTableEntity 之间进行转换。

我通常在控制器中完成变量的左右分配。

Q1

除了隐式/显式转换之外,此代码是否应该位于控制器中(x)或数据上下文(y)?

Person <--> View <--> Controller.ConverPersonHere(x?) <--> StorageContext.ConvertPersonHere(y?) <--> AzurePersonTableEntity

Q2

我应该进行隐式转换还是显式转换?

Q3

什么对象应该包含转换代码?


Update

我也在这个项目中实现 WCF,但不确定这将如何影响您的推荐。另请参阅这个问题。 https://stackoverflow.com/questions/5092736/if-wcf-is-in-a-mvc-application-should-it-use-the-controller-to-access-the-databa


Q1:控制器。

Q2:手动转换或借助 AutoMapper 等绘图工具转换。

Q3:我会将其代码放入转换器或映射器类中,如下所示。请注意,IConverter 在所有转换器之间共享,并且 IPersonConverter 的存在只是为了让您的控制器和服务定位器可以使用它。

public interface IConverter<TModel, TViewModel>
{
    TViewModel MapToView(TModel source);
}

public interface IPersonConverter : IConverter<PersonEntity, Person>
{
}

public class PersonConverter : IPersonConverter
{
    #region IPersonConverter

    public Person MapToView(PersonEntity source)
    {
        return new Person
                   {
                       ID = source.ID,
                       Name = source.Name
                   };

        //or use an AutoMapper implementation
    }

    #endregion
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用隐式/显式转换运算符是否违反单一职责模式而支持 DRY? 的相关文章

随机推荐