I have a Entity Framework generated class for one of my context items. (EF8 /.net8 Blazor Server) This class looks like this:
namespace ChargeModels
{
public partial class Individual
{
public Individual()
{
BatchLines = new HashSet<BatchLine>();
}
public int id { get; set; }
public int name { get; set; }
public int? reference { get; set; }
}
}
I want to “extend” this class to have some methods I can call directly from an “individual” object. I have created this class to do this:
namespace ChargeModels
{
public partial class Individual
{
private readonly IDbContextFactory<ChargingContext> _factory;
public Individual(IDbContextFactory<ChargingContext> factory)
{
_factory = factory;
}
public bool HasBills()
{
using (var context = _factory.CreateDbContext())
{
return context.ExistingBills.Where(x => x.IndividualId==id).Any();
}
}
}
}
In my Program.cs I do this:
builder.Services.AddDbContextFactory<ChargingContext>(options => options.UseSqlServer(config.GetConnectionString("ChargingConnection")));
With this pattern I was hoping to be able to perform this kind of operation:
public Individual BuildModel(int id)
{
var individual = _service.GetIndividual(id);
var hasBills = individual.HasBills();
}
Some of this is working as I might expect. I can get an “Individual” object from the database and it has .HasBills() available as a method I can call. The part I cannot figure out is why my _factory is always null. The overload constructor is never called leading to _factory never getting enumerated from my DI factory being passed in.
I am using the same factory in all my “normal” services just fine so I must be using this partial incorrectly.
Can anyone offer me any advice on what I am doing wrong?