Home > front end >  How would I get the auto-genereated IDs off a batch of newly inserted data?
How would I get the auto-genereated IDs off a batch of newly inserted data?

Time:12-30

I am using the .AddRange function of Entity Framework Core to insert multiple entries into the database. The only method I can find of getting the auto-generated IDs from the ID column for this data is to loop though the entities and do single query for each one. This seems highly inefficant and like I am missing something that is going to hit me in the face. What is the correct way to get back all the new IDs? My insert code:

public async Task<List<int>> UploadFile(Dictionary<IFormFile, string> files, string containerName, string connectionString)
    {
        var blobServiceClient = new BlobServiceClient(connectionString);
        var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        await containerClient.CreateIfNotExistsAsync();
        var fileIDs = new List<int>();
        var filesInfo = new List<SiteFile>();

        foreach (KeyValuePair<IFormFile, string> file in files)
        {
            var fileName = String.Concat(file.Value, ContentTypetoFileExtention.GetValueOrDefault(file.Key.ContentType));
            var blob = containerClient.GetBlobClient(fileName);
            await blob.SetHttpHeadersAsync(new BlobHttpHeaders { ContentType = file.Key.ContentType });

            using (Stream stream = file.Key.OpenReadStream())
            {
                await blob.UploadAsync(stream);
            }

            filesInfo.Add(new SiteFile()
            {
                ContainerName = containerName,
                FileName = fileName
            });
        }

        await _siteDbContext.SiteFiles.AddRangeAsync(filesInfo);
        await _siteDbContext.SaveChangesAsync();

        //Get IDs, somehow?

        return fileIDs;
    }

CodePudding user response:

Just selecting ids from filesInfo should work:

return filesInfo
    .Select(fi => fi.Id) // assuming property name is Id
    .ToList(); 

CodePudding user response:

What is the correct way to get back all the new IDs? My insert code:

Well, We can get the all the inserted ids by using a select statement over the inserted object. We can do as following:

   int[] ids = ObjectInserted.Select(x => x.ID).ToArray();

Note: In your scenario it would be

int[] ids = filesInfo.Select(x => x.fileID).ToArray(); //Or
fileIDs = filesInfo.Select(x => x.fileID).ToList();

Complete Demo:

var studentList = new List<Student>()
            {
                new Student() { Name="Kiron", Email = "[email protected]",Mobile ="123", Fname ="FName-1" },
                new Student() { Name="Matthew", Email = "[email protected]",Mobile ="234", Fname ="FName-2" },
                new Student() { Name="Guru Stron", Email = "[email protected]",Mobile ="635", Fname ="FName-3" },
                new Student() { Name="Farid", Email = "[email protected]",Mobile ="6321", Fname ="FName-4" },

            };
            _studentDbContext.Students.AddRange(studentList);
            await _studentDbContext.SaveChangesAsync();
            int[] ids = studentList.Select(x => x.ID).ToArray();

Output:

enter image description here

Note: Further details can be found here in the document

  • Related