How to write saved file id and name and URL in the Model

SaeedP

Well-known member
Joined
Oct 21, 2020
Messages
97
Programming Experience
3-5
Hello,

This code saves files on wwwroot folder:

C#:
[Route("WeatherForecast/Post")]
        [HttpPost]
        public IActionResult Post([FromForm] FileModel file)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

                using (Stream stream = new FileStream(path, FileMode.Create))
                {

                    file.FormFile.CopyTo(stream);

                }

                return StatusCode(StatusCodes.Status201Created);

            }

            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

How to save Id and name and URL in the model? is it possible for a controller to do these tasks?

regards,
 
Yes, you would just code to add also save the Id, name, and URL in the controller to do that. Exactly how you write that code depends on where you are planning of persisting the data to.

If this FileModel is the same one as from your other thread, have you figured out how to get EF to create the database? Once the database is created, you can call the appropriate EF methods to perform the save.
 
You need to
Hello,

This code saves files on wwwroot folder:

C#:
[Route("WeatherForecast/Post")]
        [HttpPost]
        public IActionResult Post([FromForm] FileModel file)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

                using (Stream stream = new FileStream(path, FileMode.Create))
                {

                    file.FormFile.CopyTo(stream);

                }

                return StatusCode(StatusCodes.Status201Created);

            }

            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

How to save Id and name and URL in the model? is it possible for a controller to do these tasks?

regards,
You need to Create Model First, create a new class in "Models" folder or somehwere in your project.

name it as "FileDetails.cs"


C#:
public class FileDetails{
    public string Id {get;set;}
    public string URL {get;set;}
}

Something like this and save it in database using EF core if needed.
 
It sounds like you need to do more research on Entity Framework. You need to create an instance of your FileContext class and all your EF operations go through that. You would create and populate a FileModel object, add that to the FileModels collection on the context and then call SaveChanges.
 
Here's a method from the service layer of an application that I'm working on right now that adds or edits an entity:
C#:
public async Task<ResultWithValidation> SaveOrganisationAsync(OrganisationDto organisationDto)
{
    if (organisationDto.OrganisationId == 0 && (!CanAdd || CustomAdd))
    {
        throw new InvalidOperationException("Entities of type 'Organisation' cannot be added.");
    }

    if (organisationDto.OrganisationId != 0 && (!CanEdit || CustomEdit))
    {
        throw new InvalidOperationException("Entities of type 'Organisation' cannot be edited.");
    }

    var resultWithValidation = new ResultWithValidation
    {
        ValidationErrors = organisationDto.OrganisationId == 0
            ? await ValidateForAddAsync(organisationDto).ConfigureAwait(false)
            : await ValidateForEditAsync(organisationDto).ConfigureAwait(false)
        };

    if (resultWithValidation.IsValid)
    {
        using var scope = serviceScopeFactory.CreateScope();

        var dbContext = scope.ServiceProvider.GetRequiredService<EyeOnTheReefDbContext>();

        var organisation = organisationDto.OrganisationId == 0
            ? new Organisation()
            : await dbContext.Organisations
                .AsTracking(QueryTrackingBehavior.TrackAll)
                .FirstOrDefaultAsync(o => o.OrganisationId == organisationDto.OrganisationId)
                .ConfigureAwait(false);

        if (organisation != null)
        {
            mapper.Map(organisationDto, organisation);

            if (organisationDto.OrganisationId == 0)
            {
                dbContext.Organisations.Add(organisation);
            }

            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            // Map back to dto so that the updated value is returned.
            mapper.Map(organisation, organisationDto);

            resultWithValidation.Result = true;
        }
    }

    return resultWithValidation;
}
I've highlighted the lines that are of particular interest to you, i.e. the ones that create the context, create the entity, populate the entity, add the entity to the context and save the changes from the context back to the database. You might create your context directly rather than using a service provider and you might populate your entity directly rather than using a mapper, but the steps are the same. We're also using async/await where we can but you might prefer synchronous methods, e.g. SaveChanges rather than SaveChangesAsync.
 
Back
Top Bottom