Insert multiple image paths in database

I have a problem with storing multiple image paths in the database. My problem is every time I try to store the image path, only the last path is saved in the database. I don’t know why. The code saves images in the directory currently but can’t save in the database. What can I do to resolve this?

My models:

public class Product
{
    [Key]
    public int ProductId { get; set; }

    [Required]
    public int CategoryId { get; set; }

    public int? SubCategory { get; set; }

    [Required]
    public int BrandId { get; set; }


    
    [Display(Name = "نام محصول")]
    [Required(ErrorMessage = "لطفا{0} را وارد کنید ")]
    [MaxLength(450, ErrorMessage = " {0} نمیتواند بیشتر از {1} کاراکتر باشد")]
    public string ProductTitle { get; set; }

    [Display(Name = "شرح محصول")]
    [Required(ErrorMessage = "لطفا{0} را وارد کنید ")]
    public string ProductDiscription { get; set; }
    [Display(Name = "قیمت محصول ")]
    [Required(ErrorMessage = "لطفا{0} را وارد کنید ")]
    public int ProductPrice { get; set; }
    [MaxLength(600)]
    public string Tags { get; set; }

    public string ProductMoreInfo { get; set; }
    [MaxLength(50)]
    public string ProductMainImage { get; set; }
    [Required]
    public DateTime CreateDate { get; set; }
    public DateTime? UpdateDate { get; set; }




    #region Relation

    [ForeignKey("CategoryId")]
    public ProductCategory ProductCategory { get; set; }

    [ForeignKey("SubCategory")]
    public ProductCategory Category { get; set; }

    public Brand Brand { get; set; }

    public List<ProductAttribute> ProductAttributes { get; set; }
    public ProductGallery ProductGallery { get; set; }
    #endregion

public class ProductGallery
{
    [Key]
    public int ImageId { get; set; }

    public int ProductId { get; set; }
    [Display(Name = "نام تصویر")]
    public string ImageUrl { get; set; }

   



    #region Relation

    public Product Product { get; set; }

    #endregion
}

Here is what I have done:
 public int AddProduct(Product product, IFormFile ImgProduct, List<IFormFile> moreImg)
    {
        product.CreateDate = DateTime.Now;
        product.ProductMainImage = "";
        //TODO Check Image 
        if (ImgProduct != null)
        {
            product.ProductMainImage = NameGenerator.GenerateUniqCode() + Path.GetExtension(ImgProduct.FileName);
            string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Product/image",
                product.ProductMainImage);
            using (var stream = new FileStream(imagePath, FileMode.Create))
            {
                ImgProduct.CopyTo(stream);
            }

            _context.Add(product);
        }

        _context.SaveChanges();
      
            AddProductImageGallery(product.ProductId, moreImg);
        return product.ProductId;
        
    }

    public bool AddProductImageGallery(int productId, List<IFormFile> images)
    {
        List<ProductGallery> gallery = new List<ProductGallery>();
       //   gallery.ImageUrl = "";
        //TODO Check Image 
        if (images != null)
        {
            foreach (IFormFile img in images)
            {
                ProductGallery gallery1=new ProductGallery();
                gallery1.ProductId = productId;
                gallery1.ImageUrl = NameGenerator.GenerateUniqCode() + Path.GetExtension(img.FileName);
                string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Product/image",
                    gallery1.ImageUrl);

               
               
                using (var stream = new FileStream(imagePath, FileMode.Create))
                {
                    img.CopyTo(stream);
                }
                gallery.Add(gallery1);
            }
            _context.AddRange(gallery);
            _context.SaveChanges();

        }

       
        return true;
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The relationship that you have defined for your models is one to one + the property that you have added for your main image. therefore you cannot have more than 2 images for your model(one in your mainimage and other in your productgallery). you can make a one to many relationship between product and product gallery.

You can use this link for more information about one to many. Your controller is fine and for getting the related data you can use .include at querying using EF Core.

https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

public class Product
{
    //other properties
    public int Id { get; set; }
    public ICollection<ProductGallery> ProductGalleries { get; set; } = new HashSet<ProductGallery>();
}

public class ProductGallery
{
    //product galleries other properties

    public int ProductdId { get; set; }
    public virtual Product Product { get; set; }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x