[英]How to save chats to database context c#
I'm trying to save chats on the database but I think I'm missing some part.我正在尝试将聊天记录保存在数据库中,但我认为我遗漏了某些部分。
The context is inizialized:上下文被初始化:
public DbSet<ChatDB>? Chats { get; set; }
This is the class:这是 class:
[Serializable]
public class ChatDB
{
[Key]
public string? ConnectionId { get; set; }
public string? Username { get; set; }
public List<MessagesDB> MessagesList { get; set; }
}
[Keyless]
[NotMapped]
public class MessagesDB
{
public string? Body { get; set; }
public bool Mine { get; set; }
public string CSS => Mine ? "sent" : "received";
}
Here I'm adding messages to the database when the server receives them:在这里,当服务器接收到消息时,我将消息添加到数据库中:
var FindUser = _context.Chats!.AsEnumerable();
foreach(var chat in FindUser)
{
if(chat.Username == sender)
{
var messageslist = new MessagesDB(message, false);
chat.MessagesList.Add(messageslist); //Here it gives me error - returned null.
_context.Entry(chat).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
}
when I go through all the chats by username:当我通过用户名的所有聊天 go 时:
var FindUser = _context.Chats.AsEnumerable();
foreach (var chat in FindUser)
{
if (chat.Username == PassUserNameClicked)
{
foreach(var messages in chat.MessagesList)
{
<div class="@messages.CSS">
<div class="user">@chat.Username</div>
<div class="msg">@messages.Body</div>
</div>
}
}
}
when I build the migration it gives me all empty:当我构建迁移时,它给了我所有的空:
public partial class AddChatsToDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
Do you guys no what is going on?你们不知道这是怎么回事吗? I believe the "list" inside the class broke the migration.我相信 class 中的“列表”破坏了迁移。
If anyone needs I figured it out, this is the class:如果有人需要我想通了,这是 class:
[Serializable]
public class ChatDB
{
[Key]
public string? ConnectionId { get; set; }
public string? Username { get; set; }
public MessagesDB? MessagesDBs { get; set; }
}
[Serializable]
public class MessagesDB
{
[Key]
public string? Id { get; set; }
public string? WhoIs { get; set; }
public string? Body { get; set; }
public bool Mine { get; set; }
public DateTime Time { get; set; }
public string? ConnectionId { get; set; }
public string CSS => Mine ? "sent" : "received";
}
Just compile it, c# will connect the two classes via "ConnectionId".只需编译它,c# 将通过“ConnectionId”连接这两个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.