How to use sessions?
Session data is the user data in every separate chat.
Session is an EF-Entity with shared primary key - UserID
and ChatID
.
There is a recommended way to use sessions via built-in Listener async methods GetSession(Message | CallbackQuery)
and SaveChanges()
.
But you can sure use session natively for more complex operations as a EntityFramework Core Database.
Built-in Way (Recommended where possible)
- In your listener/command
Handler()
/Run()
/RunAsync()
method initialize a Session variable and passMessage
orCallbackQuery
:
public override async Task Handler(Context context, CancellationToken cancellationToken)
{
var session = await GetSession(context.Update.Message);
}
- Get all values you want from session:
public override async Task Handler(Context context, CancellationToken cancellationToken)
{
var session = await GetSession(context.Update.Message);
Console.WriteLine(session.Name);
}
- Change all values you want:
public override async Task Handler(Context context, CancellationToken cancellationToken)
{
var session = await GetSession(context.Update.Message);
Console.WriteLine(session.Name);
session.Name = "[VIP] " + session.Name;
}
- Save your changes with
SaveChanges()
method:
public override async Task Handler(Context context, CancellationToken cancellationToken)
{
var session = await GetSession(context.Update.Message);
Console.WriteLine(session.Name);
session.Name = "[VIP] " + session.Name;
await SaveChanges();
}
- Complete! Now you can start your bot and test your new session-ful business logic.
Entity Framework Way
- In any place of your code get database context:
SessionContext db = Database.GetConnection().SessionContext;
- Then you can perform some Entity Framework Core operations:
using (SessionContext db = Database.GetConnection().SessionContext)
{
session = await db.FindAsync<Session>(
message.Chat.Id,
userId
);
}
- Complete! Now you can start your bot and test your new session-ful business logic.