Home > Software engineering >  Code for checking if file/record already exists
Code for checking if file/record already exists

Time:01-05

I have an application that allows you to upload and download files.

During creation of files, I want to go into the database and check if the same file no already exists and also check if a field called VendorId is the same as the vendor id they are trying to create.

For example: List view In this image, you can see I have two files already existing with the same file no, but they have different VendorId's assigned.

Creating a file

When creating a file they enter a file no, and type and then select a vendor to assign the file to.

If they try to create another file with the same file number AND also the same vendorId then I want an error to occur.

The problem I have with the following code is:

public async Task<IActionResult> OnPostAsync()
        {
            var file = _context.Files.Where(x =>x.Number ==Files.Number).FirstOrDefault();
            if (!ModelState.IsValid)
            {
                return Page();
            }
            if (file == null || (file.FileType != Files.FileType) || (file.VendorId != Files.VendorId))
            {
       
                    _context.Files.Add(Files);
                    await _context.SaveChangesAsync();
                    if (Files.FileType == "Purchase Order")
                    {
                        return LocalRedirect("~/PurchaseOrders");
                    }
                    else if (Files.FileType == "Remittance")
                    {
                        return LocalRedirect("~/Remittance");
                    }
                    else if (Files.FileType == "Growers Return")
                    {
                        return LocalRedirect("~/GrowersReturn");
                    }
                    else if (Files.FileType == "Haulage Self Bill")
                    {
                        return LocalRedirect("~/HaulageSelfBill");
                    }
                    else
                    {
                        return RedirectToPage("./Index");
                    }
            }
            else
            {
                ViewData["error"] = "Exists";
            }
            return Page();
        }

That once it finds a file with the same file number, it stops there and I need it to repeat and check for every file in the db.

Can someone advise how I would change my code to reflect this?

CodePudding user response:

You should check for both conditions (vendor and no) in the predicate of FirstOrDefault var file = _context.Files.FirstOrDefault(x => x.Number == Files.Number && x.Vendor == Files.Vendor). It will be NULL if it doesn't exist (because FirstOrDefault returns NULL if no element is matched)

Note that in your original code you were using Where then FirstOrDefault when FirstOrDefault already iterates all the items (so you were iterating twice)

  • Related