Pass value of equal properties, different classes

Asked

Viewed 494 times

1

I need the next one I don’t know if you can do, so the question, I have two classes and in these two classes I possess exactly equal properties, as follows the examples:

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 was 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 customer to the supplier the properties with the same name received the customer’s values, like:

fornecedor.FisicaJuridica = cliente.FisicaJuridica;

I just need to know if it’s possible, or a better way for me to do it, without having to go propertied by property and assigning values, the classes above are just examples the real ones are giant, it would take a lot of work.

1 answer

3


You can’t match objects of different types directly like this, unless they implement the same interface.

One suggestion is to do by Reflexion, or still 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 in a very simple way, and you can still manually implement how it would be the property "transformations" with similar values, but with different names/types.

Here’s an example of code for your case, which would be something like:

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

Here’s an example of how to set up the Automapper: Configuring Automapper

Browser other questions tagged

You are not signed in. Login or sign up in order to post.