dannyriv
dannyriv

Reputation: 87

How to work with File Uploading onto Database in .NET Core

I am learning .NET and am trying to implement a file uploading feature on my web app. I have a table in my SQL Server called 'Projects' and it has a column named 'FileUpload' which would contain the File Uploaded by the user and is of type VARBINARY(MAX). The File would be a document such as a word doc. What type would the 'FileUpload' column be in EF? And, how would I convert a stored procedure which returns a 'FileUpload' column and convert it into the entity framework's type? This is the structure of what I have:

Project.cs

 [Table("Project")]
    public class Project
    {
        [Key] 
        public int ProjectId { get; set; }
        public String ProjectName { get; set; }
        public String ProjectDescription { get; set; }
        public int FileUpload { get; set; }    //what type should it be?
        public int SubCategoryId { get; set; }
    }

Called in this stored procedure

public IEnumerable<Project> GetAllProjects(int SubCategoryId, int UserId)
        {
            List<Project> lstProjects = new List<Project>();

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("GetAllProjects", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(("@SubCategoryId"), SqlDbType.Int).Value = SubCategoryId;
                    cmd.Parameters.Add(("@UserId"), SqlDbType.Int).Value = UserId;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Project project = new Project();

                        project.ProjectName = rdr["ProjectName"].ToString();
                        project.ProjectDescription = rdr["ProjectDescription"].ToString();
                        project.FileUpload = rdr["FileUpload "].ToString();      //How would I rearrange this if it is not
                                                                                        //a string or an int?



                        lstProjects.Add(project);
                    }
                    con.Close();
                }
            }
            return lstProjects;
        }

What will be the best approach to tackle implementing file uploading? Is my approach so far in the right direction with how I call the stored procedure and implement Project.cs? What type would FileUpload be in Project.cs and in the stored procedure call?

Upvotes: 0

Views: 312

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89434

For varbinary(max) use either byte[] or access it using streaming.

Upvotes: 3

Related Questions