How to instantiate a part of a class with Entityframework working with CRUD only on these data

Asked

Viewed 122 times

1

I am creating a solution for the web in the Singlepageaplication (SPA) type made with Aspnetcore and I use the Entity Framework to make my CRUD in the SQL Server database. I am sure that the Entity Framework allows me to update only what to change in a class so I intend to structure my frontend so that it only sends the attributes to the server that have changed, for example:

Pessoa.Cs (the class with all attributes)

internal class Pessoa 
{
    public string primeiroNome { get; set; }
    public string segundoNome { get; set; }
    public int idade { get; set; }
    public string cpf { get; set; }
    // ... mais outros inúmeros campos
}

This class is used in mine controller to receive the CRUD coming from the frontend being:

GET = SELECT | POST = INSERT | PUT = UPDATE | DELETE = DELETE

Personal controler.Cs (part of the control that receives ajax as an example)

internal class PessoaController 
{

    [HttpPut("/")]
    internal IActionResult Update([FromBody] Pessoa pessoa)
    {
       // ... todo o tratamento que preciso para salvar no EF 
    }

}

Ajax request that is made from my frontend for the update (thinking of a simple call using jQuery as example)

(function(){
    // exemplo de atualização só do nome da pessoa
    var pessoa = { nome: 'teste 123' };
    $.ajax({
        method: 'put',
        url: '/',
        data: JSON.stringify(pessoa)
        success: function(res){ console.log('success', res); },
        error: function(res){ console.log('error', res); }
    })
})();

My question is the following: how can I "configure" the Entityframework so that it always receives a class and, if the attribute is null it does not update it in the database? Is there any way to set this up?

Note: the intention of this is to reduce the load of data traffic between the frontend and the backend, so I could save resources on both sides.

  • Needs to be a solution using only EF?

  • my work is on the front-end and I am obliged to integrate the back-end library (the solution has desktop and web modules)...

1 answer

1


Leandroluk, I recommend that to improve the integrity of your code use some practices:

1 - Set database column to 'not null';

2 - Use Annotation '[Required]' in the attributes of your class; Example:

internal class Pessoa 
{
    [Required]
    public string primeiroNome { get; set; }
    [Required]
    public string segundoNome { get; set; }
    public int idade { get; set; }
    [Required]
    public string cpf { get; set; }
    // ... mais outros inúmeros campos
}

3 - In your controller, when receiving the object of type 'Person', validate whether its state is valid as follows:

internal class PessoaController 
{
    private DbContext db;

    [HttpPut("/")]
    internal IActionResult Update([FromBody] Pessoa pessoa)
    {
       if (ModelState.IsValid)
       {
          //aqui você escreve o código para atualizar
          //Exemplo: 
          db.Pessoas.Update(pessoa);
          db.SaveChanges();

          return Ok();
       }
       else
       {
          return BadRequest(ex.Message);
       }
    }

}
  • My idea is exactly the opposite, is I don’t need to create multiple classes that are the same thing, ex Pessoa { login, senha } (would be for user or Pessoa {nome, sobrenome, id} (would be for simple listing) or Pessoa { ...todos os campos... } would be for detailed listing. What I want to do is something like the interfaces that exist in Typescript, which has "optional" fields".

  • 1

    So, but according to good software architecture practices, you can’t get out of that way much. I suggest that for each entity, you have a DTO (Data Transfer Object) with exactly the minimum data you need. You do not need to create MULTIPLE. Only 2. For each Domain Entity and a DTO. Example: Domain Entity - Person with all attributes; DTO - Person with only attributes you want to return/transfer between one layer and another; (Model-View/View-Model).

  • I understand. so unfortunately there is no way to simplify structures with c#... I guess then I’ll have to change the [FromBody] aspnetcore standard for it to accept receiving generic objects (which by default is blocked) and from then on make the necessary treatments...

Browser other questions tagged

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