Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor Server App not recognizing EF Entity (Weird!)

$
0
0

I'm relatively new to Blazor and developing a couple of Apps using .NET 8. No matter what I try, I cannot get EF to recognize a perfectly valid model that was working fine on it's old MVC application. I have a DB with several tables that the app connects to perfectly fine to read data and display in the front end.

I currently successfully write to a table but I use

_dbContext.Database.ExecuteSqlRawAsync()

rather than

_dbContext.Add(x);

and

await _dbContext.SaveChangesAsync();

I do need to use EF & Models though due to the migration of larger applications in the future.

To be clear, my service is registered as scoped:

builder.Services.AddDbContext<ArcadiaContext>(options => options.UseSqlServer(arcadiaConnectionString));builder.Services.AddScoped<ArcadiaLogging>();

The context file is perfectly OK:

public class ArcadiaContext : DbContext{    public ArcadiaContext() { }    public ArcadiaContext(DbContextOptions<ArcadiaContext> options) : base(options)    {        Console.WriteLine("Registered Entity Types:");        foreach (var entityType in Model.GetEntityTypes())        {            Console.WriteLine($"- {entityType.ClrType.Name}");        }    }    public DbSet<Item>? Item { get; set; }    public DbSet<DrugFormat>? DrugFormat { get; set; }    public DbSet<Packs>? Pack { get; set; }    public DbSet<PackType>? PackType { get; set; }    public DbSet<HistoricalExcelData> HistoricalExcelData { get; set; }    public DbSet<Gc_ReferenceDrugsDb> Gc_ReferenceDrugs { get; set; }    public DbSet<ArcadiaLogging> ArcadiaLoggings { get; set; }    protected override void OnModelCreating(ModelBuilder modelBuilder)    {        modelBuilder.Entity<Gc_ReferenceDrugsDb>()            .HasKey(g => new { g.BNF_Drug_ID, g.DmdId, g.VmppId });    }}

Here are the two methods of interest being called. Note it fails at _dbContext.Add(log);:

public async Task<int> RemoveDrug(int drugId, long dmdId, string gcukCode, long VmppId){    var drugToRemove = _dbContext.Gc_ReferenceDrugs            .Where(x => x.BNF_Drug_ID == drugId && x.DmdId == dmdId.ToString() && x.VmppId == VmppId.ToString())            .FirstOrDefault();    if (drugToRemove != null)    {        await _dbContext.Database.ExecuteSqlRawAsync("DELETE FROM Gc_ReferenceDrugs WHERE BNF_Drug_ID = {0} AND DmdId = {1} AND VmppId = {2}",                drugId, dmdId, VmppId);        ArcadiaLogging logObject = new ArcadiaLogging(DateTime.Now, "Remove Drug", _environment, null, $"{gcukCode}-{drugId}-{dmdId}-{VmppId}", null);        await LogAction(logObject);        return 1;     }    else    {        return 0;    }}private async Task LogAction(ArcadiaLogging log){    try    {        var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();        log.User = authState.User.Identity?.Name ?? "Unknown User";        _dbContext.Add(log);         await _dbContext.SaveChangesAsync();    }    catch (Exception ex)    {        Console.WriteLine($"Error in LogAction: {ex.Message}");        Console.WriteLine(ex.StackTrace);        throw;     }}

Here is the error:

Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit '5oJXt_WWhtJwsWMXhidjCf8cJLSfm_fntT7xHrYtNAk'.

System.InvalidOperationException: The entity type 'ArcadiaLogging' was not found. Ensure that the entity type has been added to the model.

Finally, the model class looks like this:

public class ArcadiaLogging{    [Key]    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]    public int Id { get; set; }    public string? User { get; set; }    public DateTime? DtTm { get; set; }    public string? Action { get; set; }    public string? IsLive { get; set; }    public string? DrugAdded { get; set; }    public string? DrugRemoved { get; set; }    public string? Download { get; set; }    public ArcadiaLogging() { }    public ArcadiaLogging(DateTime? dtTm, string? action, string? isLive, string? drugAdded, string? drugRemoved, string? download)    {        DtTm = dtTm;        Action = action;        IsLive = isLive;        DrugAdded = drugAdded;        DrugRemoved = drugRemoved;        Download = download;    }}

Simple stuff that has always worked for me when working with .NET 6 & ASP.NET Core MVC / Web API applications, but I have tried lots of different things. Deleted the logging table and ran through adding another migration and adding it to the DB no problems. I've inspected the _dbContext object and all the tables from the DB are elements in there, including the logging table I'm trying to write to.

I just cannot figure out what's wrong. I'm either missing something stupid or the way Blazor Server apps work is causing some issues. Be interesting to know if others have experienced this issue at all.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>