MongoDB into ASP.Net

My Brains hurts but i thing it will work

MongoDB into ASP.NET

Add an entity model

  1. Add a Models directory to the project root.

  2. Add a Book class to the Models directory with the following code:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace SmartGrownBackend.Models;

public class PiData
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }

    [BsonElement("Name")]
    public Date Datetime { get; set; }

    public decimal Roomtemp { get; set; }

    public decimal SoilWettnes { get; set; } = null!;

    public decimal Airhumidity { get; set; } = null!;
}

Add a configuration model

  1. Add the following database configuration values to appsettings.json:

{
    "DataMiningDatabase": {
        "ConnectionString": "mongodb://localhost:27017",
        "DatabaseName": "SmartGrown",
        "DataMining": "RaspiDataMining"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*"
}
  1. Add a DataMiningDatabaseSettings class to the Models directory with the following code:

 namespace SmartGrownBackend.Models;

public class DataMiningDatabaseSettings
{
    public string ConnectionString { get; set; } = null!;

    public string DatabaseName { get; set; } = null!;

    public string Datamining { get; set; } = null!;
}

The preceding DataMiningDatabaseSettings class is used to store the appsettings.json file's DataMiningDatabase property values. The JSON and C# property names are named identically to ease the mapping process.

  1. Add the following highlighted code to Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.Configure<DataMiningDatabaseSettings>(
    builder.Configuration.GetSection("DataMiningDatabase"));

In the preceding code, the configuration instance to which the appsettings.json file's DataMiningDatabase section binds is registered in the Dependency Injection (DI) container. For example, the DataMiningDatabaseSettings object's ConnectionString property is populated with the DataMiningDatabase:ConnectionString property in appsettings.json.

  1. Add the following code to the top of Program.cs to resolve the DataMiningDatabaseSettings reference:

using SmartGrownBackend.Models;

Add a CRUD operations service

  1. Add a Services directory to the project root.

  2. Add a DataMiningService class to the Services directory with the following code:

using SmartGrownBackend.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;


namespace SmartGrownBackend.Service;
{
    private readonly IMongoCollection<RaspiDataMining> _miningCollection;
    
    public DataMiningService(
        IOptions<DataMiningDatabaseSettings> dataMiningDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                dataMiningDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                dataMiningDatabaseSettings.Value.DatabaseName);

            _miningCollection = mongoDatabase.GetCollection<<RaspiDataMining>(
                dataMiningDatabaseSettings.Value.DataMining);

        }
        public async Task<List<>>
        public async Task<List<RaspiDataMining>> GetAsync() =>
            await _miningCollection.Find(_ => true).ToListAsync();

        public async Task<List<RaspiDataMining>> GetAsync(string id) =>
            await _miningCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(RaspiDataMining newData) =>
            await _miningCollection.InsertOneAsync(newData);

        public async Task UpdateAsync(string id, RaspiDataMining updateData) =>
            await _miningCollection.ReplaceIneAsync(x => x.Id == id, updateData);

        public async Task RemoveAsync(string id) =>
            await _miningCollection.DeleteOneAsync(x => x.Id == id);
}

In the preceding code, a DataMiningDatabaseSettingsinstance is retrieved from DI via constructor injection. This technique provides access to the appsettings.json configuration values that were added in the Add a configuration model section.

  1. Add the following highlighted code to Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.Configure<DataMiningDatabaseSettings>(
    builder.Configuration.GetSection("DataMiningDatabase"));

builder.Services.AddSingleton<DataMiningService>();

In the preceding code, the DataMiningService class is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate because DataMiningService takes a direct dependency on MongoClient. Per the official Mongo Client reuse guidelines, MongoClient should be registered in DI with a singleton service lifetime.

  1. Add the following code to the top of Program.cs to resolve the DataMiningService reference:

using SmartGrownBackend.Service;

Add a Controler

Add a DataMiningController class to the Conreollers with the following code:

using SmartGrownBackend.Models;
using SmartGrownBackend.Services;
using Microsoft.AspNetCore.Mvc;

namespace SmartGrownBackend.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DataMiningController : ControllerBase
{
    //ich bin wirklich müde aber ich kann nicht aufhören
    private readonly DataMiningService _dataMiningService;
    public DataMiningController(DataMiningService dataMiningService) =>
        _dataMiningService = dataMiningService;


    [HttpGet]
    public async Task<List<RaspiDataMining>> Get()=>
        await _dataMiningService.GetAsync;
    
    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<RaspiDataMining>> Get(sting id)
    {
        var raspiDataMining = await _dataMiningService.GetAsync(id);
        if(raspiDataMining == null)
        {
            return NotFound();
        }
        return raspiDataMining; 
    }
    [HttpPost]
    public async Task<IActionResult> Post(RaspiDataMining newData)
    {
        await _dataMiningService.CreateAsync(newData);

        return CreatedAtAction(nameof(Get), new { id = newData.Id }, newData);
    }
    [HttpPut("{id:length(24)}")]
        public async Task<IActionResult> Update(string id, RaspiDataMining updatedData)
    {
        var raspiDataMining = await _dataMiningService.GetAsync(id);

        if (raspiDataMining is null)
        {
            return NotFound();
        }

        updatedData.Id = raspiDataMining.Id;

        await _dataMiningService.UpdateAsync(id, updatedData);

        return NoContent();
    }
        [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> Delete(string id)
    {
        var raspiDataMining = await _dataMiningService.GetAsync(id);

        if (raspiDataMining is null)
        {
            return NotFound();
        }

        await _dataMiningService.RemoveAsync(id);

        return NoContent();
    }

}
// RA RA RA RASPITUN Lover of the Raspberry Pi System

Last updated

Was this helpful?