首页 > 解决方案 > 如何将用户详细信息从数据库加载到内存中以个性化我的机器人

问题描述

我的机器人位于需要使用 OAuth 进行用户身份验证的 Web 应用程序中。当用户开始聊天会话时,我想将用户详细信息加载到内存中以个性化对话。以下是我目前的做法,但希望有更好方法的人提供建议。

private async Task OnMessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
    var name = GetUserDetails(result);

    var message = await result;

    string id = context.Activity.Id;


    string promptText = $"Hi {name}, before we start which product do you want to chat about today?";

    PromptDialog.Choice(
        context: context,
          resume: ChoiceReceivedAsync,
          options: (IEnumerable<SoftwareOptions>)Enum.GetValues(typeof(SoftwareOptions)),
          prompt: promptText,
          retry: "Sorry please select one of the options I listed thanks.",
          promptStyle: PromptStyle.Auto
          );
}

这个想法是该GetUserDetails方法加载用户名、名字、公司 ID 等详细信息。然后,当我的机器人响应个性化对话时,我可以根据需要从任何对话框中调用用户详细信息。

private object GetUserDetails(IAwaitable<IMessageActivity> result)
{
    var db = new LicensingDbContext();

    string id = "John.Smith";
    var user = (from u in db.AspNetUsers
            where (u.UserName == id)
            select new UserDetails
            {
                FirstName = u.FirstName
            }).ToList();

    return user.First();
}

标签: c#entity-frameworkbotframework

解决方案


private async Task OnMessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> activity)
{ 
    var userProfile = await LoadUserData(context);

    string promptText = $"Hi {userProfile.FirstName}, before we start what product do you want to chat about today?";

    PromptDialog.Choice(
        context: context,
        resume: ChoiceReceivedAsync,
        options: (IEnumerable<SoftwareOptions>) Enum.GetValues(typeof(SoftwareOptions)),
        prompt: promptText,
        retry: "Sorry please select one of the options I listed thanks.",
        promptStyle: PromptStyle.Auto
    );
}

public async Task<UserProfile> LoadUserData(IDialogContext context)
{
    LicenseDbContext db = new LicenseDbContext();

    var userProfile = (from u in db.AspNetUsers
        join c in db.Companies on u.CompanyID equals c.CompanyID
        where u.UserName == "john.smith"
        select new UserProfile()
        {
            UserName = u.UserName,
            FirstName = u.FirstName,
            CompanyId = u.CompanyID,
            ParentCompany = c.ParentCompanyID,
            }).Single();
    return userProfile;
}

推荐阅读