Saturday, July 20, 2019

Read and write with the .NET Core Entity Framework Code First stuff.

using Microsoft.EntityFrameworkCore;
using FluffyNothing.Core.Objects;
using FluffyNothing.Core.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
using System;
namespace FluffyNothing.Infrastructure.ExternalDependencies.Repositories
{
   public class PlayerRepository : IPlayerRepository
   {
      public Player FindPlayerWhileCreatingPlayerIfPlayerDoesNotExist(string ipAddress)
      {
         var optionsBuilder = new DbContextOptionsBuilder<PlayerContext>();
         using (var context = new PlayerContext(optionsBuilder.Options))
         {
            using (var transaction = context.Database.BeginTransaction())
            {
               List<Player> players = context.Players.Where(p => p.PlayerIp ==
                     ipAddress).ToList();
               switch (players.Count)
               {
                  case 0:
                     Player player = new Player();
                     player.PlayerIp = ipAddress;
                     context.Players.Add(player);
                     context.SaveChanges();
                     transaction.Commit();
                     return player;
                  case 1:
                     return players[0];
                  default:
                     throw new Exception("duplicate database entries exist for " + ipAddress);
               }
            }
         }
      }
   }
}

No comments:

Post a Comment