public IActionResult UploadToDb(UploadDataViewModel model) { bool userExists = _context.Users.Where(x => x.UserName == model.UserName).Any(); if (!userExists) { User us = new User { Id = Guid.NewGuid().ToString(), UserName = model.UserName }; _context.Users.Add(us); _context.SaveChanges(); } if (model.Files != null && model.Files.Count > 0 && model.Files[0] != null) { foreach (var file in model.Files) { var fileName = Path.GetFileName(file.FileName); bool fileExists = _context.UserFiles.Where(x => x.FileName == fileName).Any(); if (!fileExists) { var fileType = file.ContentType; Stream stream = file.OpenReadStream(); BinaryReader reader = new BinaryReader(stream); var fileContent = reader.ReadBytes((int)file.Length); var userId = _context.Users.Where(x => x.UserName == model.UserName).Select(x => x.Id).FirstOrDefault(); UserFiles uf = new UserFiles { Id = Guid.NewGuid().ToString(), FileName = fileName, FileType = fileType, UserFile = fileContent, UserId = userId }; _context.UserFiles.Add(uf); _context.SaveChanges(); ModelState.AddModelError("", "File Uploaded."); } else { ModelState.AddModelError("", "File exists."); } } } return(RedirectToAction("UploadToDatabase")); }
private void Seed() { if (!uploadDbContext.ComplainesFiles.Any()) { uploadDbContext.ComplainesFiles.Add(new ComplainesFile() { Id = 1, FileName = "Sample1", FilePath = "//efd-sam/GTO/User2", UserId = 2 }); uploadDbContext.ComplainesFiles.Add(new ComplainesFile() { Id = 2, FileName = "Sample2", FilePath = "//efd-sam/GTO/User2", UserId = 1 }); uploadDbContext.ComplainesFiles.Add(new ComplainesFile() { Id = 3, FileName = "Sample3", FilePath = "//efd-sam/GTO/User2", UserId = 2 }); uploadDbContext.SaveChanges(); } }