开发者

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

开发者 https://www.devze.com 2023-02-13 08:08 出处:网络
I need to convert between these two classes, and want to maintain DRY but not violate the Single Responsibility Pattern...

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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消