Search code examples
asp.netasp.net-coreblazorblazor-webassemblyasp.net-blazor

How can I store multiple images in a database with a Blazor application?


I have an application that shows a form to the users. The form is taken by the server and stored in a database where the information can be read on another page in the application. Part of the form takes an image, where the image is converted to a Base64 string and sent to Azure to be stored, and the URL to the image is stored in the database as a string. This all works fine. My trouble comes from trying to implement a feature where users can select multiple images.

I tried changing the string Image {get;set;} to a List<string> {get;set;} where the database would just store a list of the URLs where I could iterate through them in the application. This obviously did not work, as through some research, I learned that databases cannot store lists.

I am now wondering what I can do here. Is there a simpler way of doing this that I'm missing? What am I doing wrong?


Solution

  • I tried changing the string Image {get;set;} to a List {get;set;} where the database would just store a list of the URLs where I could iterate through them in the application. This obviously did not work, as through some research, I learned that databases cannot store lists.

    You can try to use the following methods:

    1. Add separator between the Image urls. Use string Image {get;set;} to store the image urls, the value like this: "image1url,image2url,etc" (use the , as the separator). You can consider using the String.Join Method.

    2. Create a new Image table to store the Image information (contains ID, Name, Urls), then configure one-to-many relationship between the Main table and the Image model. In the Main model, use navigation property to add the Image. Code like this:

       public class Main
       {
           public int Id { get; set; }
           public string Name { get; set; }
           public List<Image> Images { get; set; }
       }
       public class Image
       {
           public int Id { get; set; }
           public string Name { get; set; }
           public string Url { get; set; }
       }
      

      More detail information about the Entity relationship, see:

      Relationships

      Configuring One To Many Relationships in Entity Framework Core

      Saving Related Data