英文:
Data is not being written to SQL database
问题
我正在尝试使用 ASP.NET Core 6 构建具有数据持久性的实时聊天应用程序。
我的问题是:我配置了 SignalR 并且它正常工作(在 UI 上进行更改)。然而,它不会更新数据库(我使用 Entity Framework Core 以代码优先的方式)。
我的应用程序 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; }
}
}
我的聊天 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();
}
}
}
我在以下位置设置了断点:
await _dbContext.SaveChangesAsync();
程序运行到该行,但不会将任何内容保存到我的数据库(迁移成功,我得到了与我的消息模型同名的数据库)。
英文:
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)
答案1
得分: 1
我解决了。
显然是我在迁移后更改了字段名称。
迁移文件无法找到模型上对应的字段。
英文:
I solved it.
It's appearently I changed field names after migration.
Migration file could not find corresponding fields on model.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论