Johannes M
Johannes M
CC#
Created by Johannes M on 8/24/2023 in #help
✅ AutoMapper - mapping record to a class (.NET 7)
Shucks that is gonna be a tedious effort for each and everytime a new record is added and a particular mapping is required.
12 replies
CC#
Created by Johannes M on 8/24/2023 in #help
✅ AutoMapper - mapping record to a class (.NET 7)
Would I then have to create a map profile for each and every mapping I will do? Is there a way I can just make it generic to automatically map the properties?
12 replies
CC#
Created by Johannes M on 8/24/2023 in #help
✅ AutoMapper - mapping record to a class (.NET 7)
Unfortunately not. Just that and that's all. But I was able to narrow it down to that it's an issue when I try map a record with a class.
12 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
Thank you so much @tarcisioo 🙏🏽
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
@tarcisioo Even add-migration TryingToAddOne just worked now. This is really weird
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
@tarcisioo That worked. Thank you so much but now does that mean I have to run this long long command each time I want to create a migration?
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
When using Visual Studio I normally go for the package manager console which then allows me to just run add-migration {migration name}
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
Command: dotnet ef migrations add TryingANewOne Exception:
Build started...
Build succeeded.
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Build started...
Build succeeded.
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
Yeah that was the first error I was getting then installed EF Core Design and then I got the error that it could not create object of type ApplicationDbContext
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
Before using the design factory I was using a normal db factory and this was not working
public class BlazorContextFactory<TContext> : IDbContextFactory<TContext> where TContext : DbContext
{
private readonly IServiceProvider _provider;

public BlazorContextFactory(IServiceProvider provider)
{
this._provider = provider;
}

public TContext CreateDbContext()
{
if (_provider == null)
{
throw new InvalidOperationException(
$"You must configure an instance of IServiceProvider");
}

return ActivatorUtilities.CreateInstance<TContext>(_provider);
}
}
public class BlazorContextFactory<TContext> : IDbContextFactory<TContext> where TContext : DbContext
{
private readonly IServiceProvider _provider;

public BlazorContextFactory(IServiceProvider provider)
{
this._provider = provider;
}

public TContext CreateDbContext()
{
if (_provider == null)
{
throw new InvalidOperationException(
$"You must configure an instance of IServiceProvider");
}

return ActivatorUtilities.CreateInstance<TContext>(_provider);
}
}
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
Was not getting any exception except for the one when trying to create a migration in the terminal. But for some odd reason when I added the context factory and added the configuration builder in the context I was able to create the migrations and update the database.
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
I have an extensions class
public static class InitialiserExtensions
{
public static async Task InitialiseDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();

var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();

await initialiser.InitialiseAsync();
}
}

public class ApplicationDbContextInitialiser
{
private readonly ApplicationDbContext _context;
private readonly ILogger<ApplicationDbContextInitialiser> _logger;

public ApplicationDbContextInitialiser(ApplicationDbContext context, ILogger<ApplicationDbContextInitialiser> logger)
{
_context = context;
_logger = logger;
}

public async Task InitialiseAsync()
{
try
{
await _context.Database.MigrateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while initialising the database");
throw;
}
}
}
public static class InitialiserExtensions
{
public static async Task InitialiseDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();

var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();

await initialiser.InitialiseAsync();
}
}

public class ApplicationDbContextInitialiser
{
private readonly ApplicationDbContext _context;
private readonly ILogger<ApplicationDbContextInitialiser> _logger;

public ApplicationDbContextInitialiser(ApplicationDbContext context, ILogger<ApplicationDbContextInitialiser> logger)
{
_context = context;
_logger = logger;
}

public async Task InitialiseAsync()
{
try
{
await _context.Database.MigrateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while initialising the database");
throw;
}
}
}
in my infra DI container
services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
services.AddScoped<ApplicationDbContextInitialiser>();
services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
services.AddScoped<ApplicationDbContextInitialiser>();
then in my program.cs
if (app.Environment.IsDevelopment())
{
using (var scope = app.Services.CreateScope())
{
try
{
app.UseMigrationsEndPoint();
await app.InitialiseDatabaseAsync();
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred during database initialization.");

throw;
}
}
}
if (app.Environment.IsDevelopment())
{
using (var scope = app.Services.CreateScope())
{
try
{
app.UseMigrationsEndPoint();
await app.InitialiseDatabaseAsync();
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred during database initialization.");

throw;
}
}
}
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
I have that statement in my program.cs but when I add a new entity and try creating a migration for it, that's when it fails at times even if I have my web project as the startup project and have the EF Core Tools and EF Core Design packages installed
34 replies
CC#
Created by Johannes M on 8/18/2023 in #help
✅ EF Core migrations at design time using Clean Architecture - .NET 7
When I had a look at the microsoft docs it recommended using this particular factory if I wanted to run migrations and when implementing it like it seems to work but I don't trust that this will work well when doing a deployment. Error: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time
34 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
Alright, I will have to find a workaround for this. Thank you @pobiega
28 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
You're right. Unfortunately I do not know of the best way to implement the session state scenario without having to constantly hit the db to populate the session values per request. because I can do it when a user logs in but when the auth session is still valid it basically hits the home controller and continues to try access the session state values to run other methods
28 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
@pobiega we are basically trying to imitate what a JS framework can do in terms of having Global State that only get mutated when needs be.
28 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
The whole menu stuff are part of the layout and change based off of some of the values (it is a multi-tenant system) so certain things like user permissions and actions are based off those values that get stored in session and then the menu will render based on what is set in the session. if you have permissions for a certain path it will show and if not it will not show.
28 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
What would you say would be the best way of keep track of variables that should stay constant throughout a session's lifetime i.e. I have some helper classes that use the values stored in the session to dynamically create menu items for the sidebar and topbar?
28 replies
CC#
Created by Johannes M on 7/24/2023 in #help
❔ Using HttpContext outside of a controller/request pipeline (.NET 7)
Does not need to be static but that was the previous implementation done with framework 4.8, I basically need to bring this up to .NET 7 standards of doing things. A lot of data was stored inside of the session state so that it can be pulled at any point in time using some thing like
public static class cCore {
public static int ClientID
{
get { return Convert.ToInt32(HttpContext.Current.Session["clientid"]); }
set { HttpContext.Current.Session["clientid"] = value; }
}
}


public class SettingsController : Controller {
public ActionResult SetUserSettings(TModel model) {
var userSettings = cUser.SaveUserSettings(model, cCore.ClientID);
}
}
public static class cCore {
public static int ClientID
{
get { return Convert.ToInt32(HttpContext.Current.Session["clientid"]); }
set { HttpContext.Current.Session["clientid"] = value; }
}
}


public class SettingsController : Controller {
public ActionResult SetUserSettings(TModel model) {
var userSettings = cUser.SaveUserSettings(model, cCore.ClientID);
}
}
So basically instead of constantly reaching out and getting that session state value, you have a class that just does that and you can call the prop.
28 replies