MqttApps/mqttApi/src/Mqtt.app.Persistencia/Services/PersistenciaService.cs

106 lines
3.1 KiB
C#

using Mqtt.App.Persistencia.Configurations;
using Mqtt.App.Application.Interfaces;
using Mqtt.App.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mqtt.App.Domain.Entities.Mqtt;
namespace Mqtt.App.Persistencia.Services
{
public class PersistenciaService : DbContext, IPersistenciaService
{
public PersistenciaService(DbContextOptions options): base(options)
{
}
public DbSet<UserEntity> User { get; set; }
public DbSet<MqttEntity> Mqtt { get; set; }
#region user
public async Task<bool> AddUser(UserEntity user)
{
User.Add(user);
return await BoolAsync();
}
public async Task<bool> UpdateUser(UserEntity user)
{
User.Update(user);
return await BoolAsync();
}
public async Task<bool> DeleteUser(int idUser)
{
var enty= await User.FirstOrDefaultAsync(x => x.Id == idUser);
if (enty == null)
return false;
User.Remove(enty);
return await BoolAsync();
}
public async Task<bool> UpdateNoNullUser(UserEntity user)
{
var enty = await User.FirstOrDefaultAsync(x => x.Id == user.Id);
if (enty == null)
return false;
if(user.Password!=null)
enty.Password= user.Password;
if (user.LastName != null)
enty.LastName = user.LastName;
if (user.UserName != null)
enty.UserName = user.UserName;
if (user.FristName != null)
enty.FristName = user.FristName;
return await BoolAsync();
}
public async Task<List<UserEntity>> GetAllUser()
{
return await User.ToListAsync();
}
public async Task<UserEntity> GetUserById(int idUser)
{
var enty = await User.FirstOrDefaultAsync(x => x.Id == idUser);
return enty;
}
public async Task<UserEntity> GetUserByPassAndName(string pass, string name)
{
var enty = await User.FirstOrDefaultAsync(x => (x.Password == pass) && (x.UserName==name));
return enty;
}
#endregion
#region mqtt
public async Task<bool> AddMqtt(MqttEntity e)
{
Mqtt.Add(e);
return await BoolAsync();
}
#endregion
private async Task<bool> BoolAsync()
{
return await SaveChangesAsync()>0;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
EntityConfigration(modelBuilder);
}
private void EntityConfigration(ModelBuilder model)
{
//configuras entidades relaccionadas con bbdd
new UserConfiguration(model.Entity<UserEntity>());
new UserConfiguration(model.Entity<MqttEntity>());
}
}
}