How to assign a class to the whole and not only the attributes separately?

1

I have a class constructor method that when called makes a query in another database class that returns me the same class as the constructor method ( only with assigned data ), eg

public Invoice(int id)
{
   CallDB db = new CallDB();
   Invoice invoice = db.ReturnInvoice(id);
   this.Filial = invoice.Filial;
   this.UserProfileModel = invoice.UserProfileModel;
   this.DataEmissao = invoice.DataEmissao;
   this.DataVencimento = invoice.DataVencimento;
   this.ID = invoice.ID;
}

I would not like to be using this "300 thousand" times, would it be possible to do something like this?

public Invoice(int id)
{
   CallDB db = new CallDB();
   Invoice invoice = db.ReturnInvoice(id);
   this.Invoice = invoice ; //estou atribuindo a classe como um todo ao invés de cada atributo separadamente
}
    
asked by anonymous 29.12.2017 / 13:41

2 answers

2

There's no way around it.

And it seems like there are several things wrong there, starting with this class that does not seem to be what it describes. It is even difficult to give a correct direction by being in the wrong foundation.

Of course you can make ReturnInvoice() already return the mounted object, but then you will be doing the same thing you already do in the original constructor, but in another method. And worse, in the wrong method that should only handle the database.

There is a solution with reflection , but it is not usually recommended. It seems to me to be just to reduce typing and is not a good use for this. And if you need this maybe C # is not the right language for this solution.

With reflection you could read the object structure and make a #

In some cases it may facilitate reflection if you use certain conventions, but it makes it complicated to make the system that can not escape them, does not compensate.

You can also use a Invoice or a <

In C # I prefer a solution of scaffolding or do it manually.

A restructuring of the overall architecture can give a better solution.

    
29.12.2017 / 14:01
1

In this scenario, you would have to call the object this way:

Invoice obj = new Invoice(1);

Correct?

I suggest you create a static method that returns the object:

public class Invoice
{
   public Invoice()
   {
     //...construtor padrão
   }

   public static Invoice SelectById(int id)
   {
       CallDB db = new CallDB();
       return db.ReturnInvoice(id);
   }
}

And then I would call:

Invoice obj = Invoice.SelectById(1);

However ... I suggest revising the structure of your code, because within the class you are having access to the data layer, this is generating a high coupling and low cohesion which is not right and will make the code more complex and difficult maintenance.

    
29.12.2017 / 13:48