Förberett för övergång till entity framework

This commit is contained in:
2025-09-01 11:14:38 +02:00
parent eb9ea77dd9
commit b04fc7e06e
13 changed files with 191 additions and 73 deletions

View File

@ -1,5 +1,14 @@
namespace Common.Library;
//using GreadyPoang.DataLayer;
namespace Common.Library;
public class ViewModelBase : CommonBase
{
//private readonly LocalDbService _dbService;
//public ViewModelBase(LocalDbService dbService)
//{
// _dbService = dbService;
//}
}

View File

@ -6,4 +6,5 @@
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -4,7 +4,7 @@ namespace Common.Library;
public interface IRepository<TEntity>
{
ObservableCollection<TEntity> Get();
Task<ObservableCollection<TEntity>> Get();
TEntity Get(int id);
bool Save(TEntity entity);
}

View File

@ -0,0 +1,46 @@
using GreadyPoang.EntityLayer;
using SQLite;
namespace GreadyPoang.DataLayer;
public class LocalDbService
{
private const string DB_NAME = "PoangDB";
private readonly SQLiteAsyncConnection _connection;
public LocalDbService()
{
//string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DB_NAME);
string dbPath = Path.Combine(FileSystem.Current.AppDataDirectory, DB_NAME);
_connection = new SQLiteAsyncConnection(dbPath);
_connection.CreateTableAsync<Participant>().Wait();
}
public async Task<List<Participant>> GetParticipantsAsync()
{
return await _connection.Table<Participant>().ToListAsync();
}
public async Task<Participant?> GetParticipantAsync(int id)
{
return await _connection.Table<Participant>().Where(p => p.ParticipantId == id).FirstOrDefaultAsync();
}
public async Task<int> SaveParticipantAsync(Participant participant)
{
if (participant.ParticipantId != 0)
{
return await _connection.UpdateAsync(participant);
}
else
{
return await _connection.InsertAsync(participant);
}
}
public async Task<int> DeleteParticipantAsync(Participant participant)
{
return await _connection.DeleteAsync(participant);
}
}

View File

@ -6,78 +6,83 @@ namespace GreadyPoang.DataLayer;
public class ParticipantRepository : IRepository<Participant>
{
private readonly LocalDbService _dbService;
private ObservableCollection<Participant> lager;
public ParticipantRepository()
public ParticipantRepository(LocalDbService dbService)
{
if (lager == null || lager.Count == 0)
{
lager = new ObservableCollection<Participant>();
lager.Add(new Participant
{
ParticipantId = 1,
FirstName = @"Kalle",
LastName = @"Persson",
Email = @"kalle@person.com",
});
lager.Add(new Participant
{
ParticipantId = 2,
FirstName = @"Olle",
LastName = @"Goop",
Email = @"olle@goop.com",
});
lager.Add(new Participant
{
ParticipantId = 3,
FirstName = @"Nisse",
LastName = @"Pärlemo",
Email = @"nisse@parlemo.com"
});
}
_dbService = dbService;
}
#region Get Method
public ObservableCollection<Participant> Get()
public async Task<ObservableCollection<Participant>> Get()
{
// This method should return a collection of Participant objects.
// For now, returning an empty collection.
List<Participant> result = await _dbService.GetParticipantsAsync();
if (result != null)
{
foreach (var participant in result)
{
if (!lager.Any(p => p.ParticipantId == participant.ParticipantId))
{
lager.Add(participant);
}
}
}
return lager;
}
public Participant? Get(int id)
{
return Get().Where(row => row.ParticipantId == id).FirstOrDefault();
Participant? participant = null; // Initialize the variable to avoid CS0165
_dbService.GetParticipantAsync(id).ContinueWith(task =>
{
if (task.Exception == null)
{
participant = task.Result;
if (participant != null)
{
System.Diagnostics.Debug.WriteLine($"Fetched Participant by ID: {participant.ParticipantId}, {participant.FirstName}, {participant.LastName}, {participant.Email}");
}
else
{
System.Diagnostics.Debug.WriteLine($"No Participant found with ID: {id}");
}
}
else
{
// Handle exceptions as needed
System.Diagnostics.Debug.WriteLine($"Error fetching participant by ID: {task.Exception.Message}");
}
}).Wait();
return participant;
}
#endregion
public bool Save(Participant entity)
{
if (entity.ParticipantId == 0)
var output = false;
try
{
// New entity
var maxId = lager.Max(p => p.ParticipantId);
entity.ParticipantId = maxId + 1;
_dbService.SaveParticipantAsync(entity).Wait();
lager.Add(entity);
output = true;
}
else
catch (Exception ex)
{
// Existing entity
var existing = Get(entity.ParticipantId);
if (existing != null)
{
existing.FirstName = entity.FirstName;
existing.LastName = entity.LastName;
existing.Email = entity.Email;
}
else
{
return false; // Entity not found
}
System.Diagnostics.Debug.WriteLine($"Error saving participants: {ex.Message}");
}
return true;
return output;
}
}

View File

@ -0,0 +1,25 @@
using GreadyPoang.EntityLayer;
using Microsoft.EntityFrameworkCore;
namespace GreadyPoang.DataLayer.Database
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
//public DbSet<User> Users => Set<User>();
public DbSet<Participant> Participants { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Participant>().HasData(
new Participant { ParticipantId = 1, FirstName = "John", LastName = "Doe", Email = "John.Doe@gmail.com" },
new Participant { ParticipantId = 2, FirstName = "Jane", LastName = "Black", Email = "jb@gmail.com" },
new Participant { ParticipantId = 3, FirstName = "Mary", LastName = "White", Email = "mw@gmail.com" }
);
}
}
}

View File

@ -7,6 +7,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.8" />
<PackageReference Include="Microsoft.Maui.Controls" Version="9.0.100" />
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.11" />
</ItemGroup>

View File

@ -1,7 +1,8 @@
using Common.Library;
using SQLite;
namespace GreadyPoang.EntityLayer;
[Table("Participants")]
public class Participant : EntityBase
{
public Participant()
@ -16,6 +17,9 @@ public class Participant : EntityBase
private string _lastName;
private string _email;
[PrimaryKey]
[AutoIncrement]
[Column("ParticipantId")]
public int ParticipantId
{
get { return _participantId; }
@ -26,6 +30,7 @@ public class Participant : EntityBase
}
}
[Column("FirstName")]
public string FirstName
{
get { return _firstName; }
@ -36,6 +41,7 @@ public class Participant : EntityBase
}
}
[Column("LastName")]
public string LastName
{
get { return _lastName; }
@ -45,6 +51,8 @@ public class Participant : EntityBase
RaisePropertyChanged(nameof(LastName));
}
}
[Column("Email")]
public string Email
{
get { return _email; }

View File

@ -10,4 +10,8 @@
<ProjectReference Include="..\Common.Library\Common.Library.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.11" />
</ItemGroup>
</Project>

View File

@ -17,6 +17,11 @@ public class ParticipantViewModel : ViewModelBase
{
Repository = repo;
}
//public ParticipantViewModel(IRepository<Participant> repo) : base()
//{
// Repository = repo;
//}
#endregion
#region Private Variables
@ -50,14 +55,16 @@ public class ParticipantViewModel : ViewModelBase
#endregion
#region Get Method
public ObservableCollection<Participant> Get()
public async Task<ObservableCollection<Participant>> GetAsync()
{
if (Repository != null)
{
ParticipantList = new ObservableCollection<Participant>(Repository.Get());
ParticipantList = await Repository.Get();
return ParticipantList;
}
return new();
_ParticipantList = new ObservableCollection<Participant>();
return ParticipantList;
}
#endregion
@ -86,7 +93,7 @@ public class ParticipantViewModel : ViewModelBase
if (tmp)
{
ParticipantObject = new Participant();
this.Get();
this.GetAsync();
}
return tmp;
}

View File

@ -60,8 +60,9 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Maui.Controls" Version="9.0.100" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.8" />
</ItemGroup>
<ItemGroup>

View File

@ -1,12 +1,14 @@
using Common.Library;
using GreadyPoang.CommandClasses;
using GreadyPoang.DataLayer;
using GreadyPoang.DataLayer.Database;
using GreadyPoang.EntityLayer;
using GreadyPoang.Views;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace GreadyPoang
{
namespace GreadyPoang;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
@ -20,6 +22,15 @@ namespace GreadyPoang
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
builder.Services.AddDbContext<DataContext>(options =>
{
var dbPath = Path.Combine(FileSystem.Current.AppDataDirectory, "PoangDB");
options.UseSqlite($"Data Source={dbPath}");
});
builder.Services.AddSingleton<LocalDbService>();
builder.Services.AddScoped<IRepository<Participant>, ParticipantRepository>();
builder.Services.AddScoped<ParticipantViewModelCommands>();
builder.Services.AddScoped<ParticipantListView>();
@ -31,4 +42,3 @@ namespace GreadyPoang
return builder.Build();
}
}
}

View File

@ -17,7 +17,7 @@ public partial class ParticipantListView : ContentPage
{
base.OnAppearing();
BindingContext = ViewModel;
ViewModel.Get();
ViewModel.GetAsync();
}