Insert multiple values with WEB API

Asked

Viewed 36 times

-1

How are you, my dear? Quiet? I will summarize my project to assist in understanding: I am creating a CRUD to assist me in some of the company’s tasks. I have 3 areas I use (System, Database and Systemdatabase). In the area System I register the systems I use in the company, already in the Database I register all databases that my systems can use and on Systemdatabase the systems are stored together with their active databases. I am using Angular in frontend and Webapi with ASP.NET and EF CORE in backend.

In my form I inform what will be the system I will tell the banks that will be active for it, as a system can communicate with several databases, I have chosen to use a "Multiple select" to list all the banks I can add, see below:

Formulário de cadastro dos sistemas

The problem is that I don’t know exactly how to put this data in the table, and the way I did I’m not getting the return I wanted, I did a lot of research on it but there is not much content addressing this subject over the internet. I’ve read language documentation, framework documentation, I asked a colleague for help, I even searched on an Indian site and I couldn’t find much.

My logic was as follows: I thought about creating an array to store the Id of each selected database and when saving (running the POST) it runs a for which will do a check through an index and if there is data in the array, go adding in the database one by one

Lógica

To do this, I went to my Model and created a property that is an integer array called Iddatabases:

using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace ITControl.Models
{
    public partial class SystemDatabase
    {
        public int IdSystemDatabase { get; set; }
        public int IdSystem { get; set; }
        public int IdDatabase { get; set; }
        [NotMapped]
        public int[] IdDatabases { get; set; } // <============ AQUI
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UserInserted { get; set; }
        public string UserUpdated { get; set; }

        public virtual System System { get; set; }
        public virtual DataBase DataBase { get; set; }
    }
}

And I passed this logic into my controller on [HttpPost]

        [HttpPost]
        public async Task<ActionResult<SystemDatabase>> PostSystemDatabase(SystemDatabase systemDatabase)
        {
            systemDatabase.CreatedAt = DateTime.Now;
            systemDatabase.UserInserted = (HttpContext.User.Identity as ClaimsIdentity).Name;


            for (int i = 0; i < systemDatabase.IdDatabases.Count(); i++)
            {
                systemDatabase.IdDatabase = systemDatabase.IdDatabases[i];
                _context.SystemDatabase.Add(systemDatabase);
            }

            await _context.SaveChangesAsync();

            return CreatedAtAction("GetSystemDatabase", new { id = systemDatabase.IdSystemDatabase }, systemDatabase);

        }

The result I was hoping was that he would add one by one he would return something more or less to me in this footprint at the bank:

Resultado Esperado

But in reality he doesn’t add one by one, he’s just playing the last Id on the bench:

Resultado Atual

I went to the browser developer tools, looked at the response he was giving me on the network when doing the Post and he returned me the following preview:

{IdSystemDatabase: 40, IdSystem: 3, IdDatabase: 13, IdDatabases: [1, 13],…}
CreatedAt: "2020-08-25T08:54:13.5748194-03:00"
DataBase: null
IdDatabase: 13
IdDatabases: [1, 13]
0: 1
1: 13
IdSystem: 3
IdSystemDatabase: 40
System: null
UpdatedAt: null
UserInserted: "OliveiraRBru"
UserUpdated: null

He’s getting the Ids on IdDatabases but it is not registering one by one, what can I be doing wrong?? To really lost, I believe very much that the error is within mine For

  • face by the size of your question it seems to be specified from your system, try to ask a more concise and specific question of a problem

1 answer

0


By looking deeper and consulting with some other colleagues, I was able to resolve the error. I would undo the question, but as I saw that there is not much on the internet talking about it, I will share it with you and leave my contribution to the community ;D

The solution I found was the following, I removed the IdSystemDatabase of my model and my context, since my table in the database would only be used to store the system and database ID, soon it would become useless and would also keep bringing some errors, so I already tried to remove it.

My model was as follows:

using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace ITControl.Models
{
    public partial class SystemDatabase
    {
        public int IdSystem { get; set; }
        public int IdDatabase { get; set; }
        [NotMapped]
        public int[] IdDatabases { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UserInserted { get; set; }
        public string UserUpdated { get; set; }

        public virtual System System { get; set; }
        public virtual DataBase DataBase { get; set; }
    }
}

After removing the IdSystemDatabase from my context, it was necessary to pass the IdSystem and IdDatabase as key

I put the following in context:

entity.HasKey(d => new { d.IdDatabase, d.IdSystem });

Past the IdSystem and the IdDatabase like keys in context, I changed some things in my for. First I used a if to check if there were no repeated or null data, and within if I passed the condition that was previously directly in for. Checking with a breakpoint earlier, I had realized I was making a mistake, I was not asking to save the insert after checking, it received the id within the index, received the command to add but received nothing telling him to save this insertion and because of that he added in the bank only the last id passed by the index since it was the last stored in the IdDatabase, only after he came out of whatever would save, this was the mistake. Soon to correct this I passed the await _context.SaveChangesAsync(); into the condition of for everything being as follows:

        [HttpPost]
        public async Task<ActionResult<SystemDatabase>> PostSystemDatabase(SystemDatabase systemDatabase)
        {
            systemDatabase.CreatedAt = DateTime.Now;
            systemDatabase.UserInserted = (HttpContext.User.Identity as ClaimsIdentity).Name;

            for (int i = 0; i < systemDatabase.IdDatabases.Count(); i++)
            {
                if (_context.SystemDatabase.Where(w => w.IdSystem == systemDatabase.IdSystem
                                                 && w.IdDatabase == systemDatabase.IdDatabases[i]).FirstOrDefault() == null)
                {
                    systemDatabase.IdDatabase = systemDatabase.IdDatabases[i];
                    _context.SystemDatabase.Add(systemDatabase);
                    await _context.SaveChangesAsync();
                }                
            }

            return CreatedAtAction("GetSystemDatabase", systemDatabase);

        }

And that’s it, I got the desired result from the bank, look at that:

Resultado Certo

And treating the ID’s to present their respective names on CRUD, this was my final result:

inserir a descrição da imagem aqui

(I censored them because they’re company systems)

Browser other questions tagged

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