Search code examples
entity-framework-coreasp.net-core-mvcsignalr

Data is not being written to SQL database


I am trying to build real time chat app with data persistence using ASP.NET Core 6.

My problem is: I configured SignalR and it works properly (it makes changes on UI). However, it does not update the database (I am using Entity Framework Core with a code-first approach).

My application DbContext:

using Microsoft.EntityFrameworkCore;
using VGChat_demo.Models;

namespace VGChat_demo.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

        public DbSet<Message> Messages { get; set; }
    }
}

My chat hub:

using Microsoft.AspNetCore.SignalR;
using VGChat_demo.Data;
using VGChat_demo.Models;

namespace VGChat_demo.Hubs 
{ 
    public class ChatHub : Hub
    {
        private readonly ApplicationDbContext _dbContext;

        public ChatHub(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task SendMessage(string user, string content)
        {
            var message = new Message
                              {
                                  User = user,
                                  Content = content,
                                  Timestamp = DateTime.UtcNow
                              };

            _dbContext.Messages.Add(message);

            await Clients.All.SendAsync("ReceiveMessage", message.User, message.Content, message.Timestamp);
            await _dbContext.SaveChangesAsync();
        }
    }
}

I put a breakpoint on

await _dbContext.SaveChangesAsync();

Program runs to that line, but it does not save anything to my database (migration is successful, I get the database named same with my message model)


Solution

  • I solved it. It's appearently I changed field names after migration. Migration file could not find corresponding fields on model.