CodeLiturgy.Dashboard/BlueWest.Api/Extensions/ModelBuilderExtensions.cs

93 lines
2.7 KiB
C#
Raw Normal View History

2022-08-20 05:47:32 +03:00
using BlueWest.Data;
using Microsoft.EntityFrameworkCore;
namespace BlueWest.WebApi.MySQL.Model
{
/// <summary>
/// Database model configuration extensions
/// </summary>
public static class ModelBuilderExtensions
{
/// <summary>
/// Setup the database model
/// </summary>
/// <param name="modelBuilder"></param>
public static void ConfigureCurrentDbModel(this ModelBuilder modelBuilder)
{
modelBuilder
.ConfigureDatabaseKeys()
.CountryCurrencyModel()
.ConfigureUserModel();
}
private static ModelBuilder ConfigureDatabaseKeys(this ModelBuilder modelBuilder)
{
// User PK
modelBuilder.Entity<User>(builder => builder
.HasKey(user => user.Id));
// Country PK
modelBuilder.Entity<Country>(builder => builder
.HasKey(country => country.Code));
// Currency PK
modelBuilder.Entity<Currency>(builder => builder
.HasKey(currency => currency.Num));
// FinanceOp PK
return
modelBuilder.Entity<FinanceOp>(builder => builder
.HasKey(financeOp => financeOp.Id));
}
private static ModelBuilder CountryCurrencyModel(this ModelBuilder modelBuilder)
{
// Relationships
modelBuilder
.Entity<Currency>()
.HasMany(ub => ub.Countries)
.WithMany(au => au.Currencies);
modelBuilder.Entity<Country>()
.HasMany(ub => ub.Currencies)
.WithMany(au => au.Countries);
return modelBuilder;
}
private static ModelBuilder ConfigureUserModel(this ModelBuilder modelBuilder)
{
// User => Country
modelBuilder
.Entity<User>(builder => builder
.HasOne<Country>()
.WithMany(co => co.Users));
// Country => User
modelBuilder
.Entity<Country>(builder => builder
.HasMany<User>()
.WithOne(u => u.Country)
.HasForeignKey(x => x.CountryId));
// FinanceOp => User
modelBuilder
.Entity<FinanceOp>(builder => builder
.HasOne<User>()
.WithMany(ft => ft.FinanceTransactions)
.HasForeignKey(x => x.UserId));
return modelBuilder;
}
}
}