If you're trying to get a object/viewModel that contains a Byte[]/base64,
i searched in hours for a solution but then i added extra parameter to my viewmodel
public class ProductAddVM
{
public int Id { get; set; }
public Categories Category { get; set; }
public decimal Vat { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public IFormFile Image { get; set; }
public Byte[] ByteImage { get; set; }
public string Description { get; set; }
public bool? Available { get; set; }
}
The parameter Image is to store the new image that may be uploading in EDIT as you mentioned.
While the parameter ByteImage is to get the old image from Database.
The where you're done editing you can convert the IFormFile to byte[] and save it in DataBase
I tried to use Mapper but it went wrong, this code is working 100% but i'm gonna make it look better
internal ProductAddVM GetProduct(int id)
{
var model = new Product();
model = Product.FirstOrDefault(p => p.Id == id);
var viewModel = new ProductAddVM();
viewModel.Id = model.Id;
viewModel.Name = model.Name;
viewModel.Available = model.Available;
viewModel.Description = model.Description;
viewModel.Price = model.Price;
viewModel.Category = (Categories)model.Category;
viewModel.Vat = model.Vat;
viewModel.ByteImage = model.Image;
return viewModel;
}
internal void EditProduct(int id, ProductAddVM viewModel,int userId)
{
var tempProduct = Product.FirstOrDefault(p => p.Id == id);
tempProduct.Name = viewModel.Name;
tempProduct.Available = viewModel.Available;
tempProduct.Description = viewModel.Description;
tempProduct.Price = viewModel.Price;
tempProduct.Category =(int)viewModel.Category;
tempProduct.Vat = CalculateVat(viewModel.Price,(int)viewModel.Category);
if (viewModel.Image != null)
{
using (var memoryStream = new MemoryStream())
{
viewModel.Image.CopyToAsync(memoryStream);
tempProduct.Image = memoryStream.ToArray();
}
}
tempProduct.UserId = userId;
tempProduct.User = User.FirstOrDefault(u => u.Id == userId);
SaveChanges();
}