Pass value of equal properties, different classes

1

I need the following I do not know if it has how to do, So the question, I have two classes and in these two classes I have exactly the same properties,

public class Cliente
{
    public int ID { get; set; }
    public string FisicaJuridica { get; set; }
    public string NomeRazaoSocial { get; set; }
    public string ApelidoNomeFantasia { get; set; }
    public string CPFCNPJ { get; set; }
}

public class Fornecedor
{
    public int ID { get; set; }
    public string FisicaJuridica { get; set; }
    public string NomeRazaoSocial { get; set; }
    public string ApelidoNomeFantasia { get; set; }
    public string CPFCNPJ { get; set; }
}

What I needed to do would be something like:

var cliente = ctx.Clientes.Find(01);//Preenche o objeto cliente
var fornecedor = cliente;//Seria algo assim mas sei que é impossivel

What I needed, when trying the above method where I assign the client to the provider the properties with the same name would receive the values of the client, type:

fornecedor.FisicaJuridica = cliente.FisicaJuridica;

I just need to know if it's possible, or a better way for me to do this, without having to go by property and assigning values, The above classes are just examples the real ones are giants, it would work hard.

    
asked by anonymous 10.02.2017 / 05:23

1 answer

3

You can not match objects of different types directly so unless you implement the same interface.

One suggestion is to make reflection, or even use a mapper, such as AutoMapper: AutoMapper.org

With AutoMapper you can pass property values with the same name and type from one object to another quite simply, and you can still manually implement how property "transformations" would look like, but with names / types different.

See an example code for your case that would look something like:

var cliente = ctx.Clientes.Find(01);
Mapper.CreateMap(typeof(Cliente), typeof(Fornecedor));
var fornecedor= Mapper.Map<Cliente, Fornecedor>(cliente);

Here is an example of how to configure AutoMapper: Configuring AutoMapper

    
10.02.2017 / 10:39