Does using Implicit / Explicit conversion operators violate Single Responsibility Pattern in favor of DRY?

送分小仙女□ 提交于 2019-12-11 03:58:05

问题


I need to convert between these two classes, and want to maintain DRY but not violate the Single Responsibility Pattern...

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
}

More Info

I have some Model objects in my ASP.NET MVC application. Since I'm working with Azure storage I see the need to convert to and from the ViewModel object and the AzureTableEntity quite often.

I've normally done this left-hand-right-hand assignment of variables in my controller.

Q1

Aside from implicit/explicit conversion, should this code be in the controller(x) or the datacontext(y)?

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

Q2

Should I do an implicit or explicit conversion?

Q3

What object should contain the conversion code?


Update

I'm also implementing WCF in this project and am not sure how this will affect your recommendation . Please also see this question.


回答1:


Q1: The controller.

Q2: Convert manually or with the help of a mapping tool such as AutoMapper.

Q3: I would put the code for this in a converter or mapper class like the following. Note that IConverter is shared among all converters, and IPersonConverter just exists so your controllers and service locators can use it.

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
}


来源:https://stackoverflow.com/questions/5087183/does-using-implicit-explicit-conversion-operators-violate-single-responsibilit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!