Daniel Lazarte
Daniel Lazarte

Reputation: 119

How to Read a value from appsettings.json and mix it with the values ​returned by Entity Framework

Good morning, I have a Project in Asp.net Core 5 which has a Core project with entities. My question is, I need to know how to mix a property of the News Class with a value that is hosted in another ASP.Net Core API project. That is, when returning the value from Entity you must be able to mix the values ​​of appsettings.json + the image field

that is, in the GetNoticiacastList () method I need the FullPath property to mix with the values ​​of the appsettings and the value of the image property. to form a URL of the

my appsettings.json

"AppSettings": {
"virtualpath": "//google.com/photos/"

},

My class:

    public class Noticia
{
    public int  id{ get; set; }
    public string Titulo { get; set; }
    public string Imagen { get; set; }
    public string FullPath { get; set; }
}

My NoticiaRepository:

     public async Task<IEnumerable<Noticia>> GetNoticiacastList()
    {
        var listadoNoticia = await _context.Noticia.ToListAsync();
        return listadoNoticia ;
    }

Upvotes: 0

Views: 288

Answers (1)

MrMoeinM
MrMoeinM

Reputation: 2388

It's a good idea to map configuration to a class.

StorageOption.cs (create this file)

public class StorageOption
{
    public string VirtualPath { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<StorageOption>(Configuration.GetSection("AppSettings"));
    ....
}

NoticiaRepository.cs

public class NoticiaRepository : INoticiaRepository
{
    private readonly AppDbContext _context;
    private readonly StorageOption _storageOption;
    ...

    public NoticiaRepository(AppDbContext context, IOptions<StorageOption> storageOption)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
        _storageOption = storageOption?.Value ?? throw new ArgumentNullException(nameof(storageOption));
    }

    ...

    public async Task<IEnumerable<Noticia>> GetNoticiacastList()
    {
        var listadoNoticia = await _context.Noticia.ToListAsync();
        return listadoNoticia.Select(item => { item.FullPath = $"{_storageOption.VirtualPath}{item.Imagen}"; return item; });
    }

    ...
}

Upvotes: 1

Related Questions