locked
Dbcontext issue RRS feed

  • Question

  • User448619955 posted

    I'm trying to use Microsoft Bot and in my app I want to connect to my database.

    In ASP.Net core I know it should add some codes in my appsettings.json.

    here are my codes in related files such as json,class and so on.

    {
      "botFilePath": "BotConfiguration.bot",
      "botFileSecret": "",
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "ConnectionString": {
        "EmployeeDB": "server=.;database=InstaYab;User ID=blahblah;password=blahblah;"
      },
      "AllowedHosts": "*"

    my DbContext class

    using DomainClasses.Models;
    using Microsoft.EntityFrameworkCore;
    
    
    namespace DomainClasses.Classes
    {
        public class InstayabDbContext:DbContext
        {
            public InstayabDbContext(DbContextOptions<InstayabDbContext> options) :base(options)
            {
                
            }
            public DbSet<Like> Likes { get; set; }
            public DbSet<Comment> Comments { get; set; }
            public DbSet<Follow> Follows { get; set; }
    
        }
    }
    

    my startup class

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddBot<EchoWithCounterBot>(options =>
                {
                    var secretKey = Configuration.GetSection("botFileSecret")?.Value;
                    var botFilePath = Configuration.GetSection("botFilePath")?.Value;
                    services.AddMvc();
                    services.AddDbContext<InstayabDbContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("EmployeeDB")));
    ...
    ...

    and I should use my connection in this file

          public async Task StartBot(ITurnContext turnContext)
            {
                InstayabDbContext db=new InstayabDbContext();

    here I got an error

     InstayabDbContext db=new InstayabDbContext(); 

    I should pass options into InstayabDbContext() but I don't know how to do that.

    I know in ASP.Net Core app it could be pass in controller but in Microsoft Bot ,I don't know how to use it.

    Saturday, May 25, 2019 6:54 AM

All replies

  • User1120430333 posted

    here I got an error

    What error would that be?

    Myself I use a Connectionstring class and the class is dependency injected into the classes.

    The code shows how the IOption is used to get the connectionstring to the Dbcontext.

    I used the information in the link.

    https://corderoski.wordpress.com/2017/09/18/how-to-read-appsettings-json-from-class-library-in-asp-net-core/

    namespace Entities
    {
        public class ConnectionStrings
        {
            public string DefaultConnection { get; set; }
            public string ProjectManagementConnection { get; set; }
        }
    }
    
    
    {
      "ConnectionStrings": {
        "DefaultConnection": "Dummy",
        "ProjectManagementConnection":
          "Server=DESKTOP-A86QNRQ\\SQLEXPRESS;Database=ProjectManagement;User Id=SA;Password=xxxxxxxxx"
      },
      "Serilog": {
        "Using": ["Serilog.Sinks.Console"],
        "MinimumLevel": "Error",
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "RollingFile",
            "Args": {
              "pathFormat": "c:\\logsapi\\log-{Date}.txt",
              "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
            }
          }
        ],
        "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
        "Properties": {
          "Application": "My Application",
          "Logging": {
            "LogLevel": {
              "Default": "Warning"
            }
          },
          "AllowedHosts": "*"
        }
      }
    }
    
    using System.Net;
    using DAL;
    using Entities;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Diagnostics;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Serilog;
    
    namespace ProgMgmntCore2Api
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
                Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                //DAL
                services.AddTransient<IDaoProject, DaoProject>();
                services.AddTransient<IDaoTask, DaoTask>();
                services.AddTransient<IDaoCache, DaoCache>();
    
                //Configuration
                services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    
                // Add framework services.
                services.AddMvc(options =>
                {
                    options.Filters.Add(new ErrorHandlingFilter(Configuration));
    
                });
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    using System.Linq;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoCache : IDaoCache
        {
            private readonly IOptions<ConnectionStrings> _options;
          
            public DaoCache(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoCache GetCache()
            {
                var dtocache = new DtoCache
                {
                    ProjectTypes = new List<DtoProjectType>(),
                    Statuses = new List<DtoStatus>(),
                    Resources = new List<DtoResource>(),
                    Durations = new List<DtoDuration>()
                };
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var projectypes = (from a in context.ProjectTypes select a).ToList();
                    CreateProjectTypes(dtocache, projectypes);
    
                    var statuses = (from a in context.Statuses select a).ToList();
                    CreateStatuses(dtocache, statuses);
    
                    var resources = (from a in context.Resources select a).ToList();
                    CreateResources(dtocache, resources);
    
                    var durations = (from a in context.Durations select a).ToList();
                    CreateDurations(dtocache, durations);
                }
    
                return dtocache;
            }
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL.Models.DB
    {
        public partial class ProjectManagementContext : DbContext
        {
            private readonly IOptions<ConnectionStrings> _options;
            public ProjectManagementContext(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public ProjectManagementContext(DbContextOptions<ProjectManagementContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Projects> Projects { get; set; }
            public virtual DbSet<Tasks> Tasks { get; set; }
            public virtual DbSet<ProjectTypes> ProjectTypes { get; set; }
            public virtual DbSet<Durations> Durations { get; set; }
            public virtual DbSet<Resources> Resources { get; set; }
            public virtual DbSet<Statuses> Statuses { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlServer(new AppConfiguration(_options).GetProjectMgmntConn());
                }
            }
    using Entities;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class AppConfiguration
        {
            private readonly string _projectManagementConnection = "";
            private readonly IOptions<ConnectionStrings> _options;
    
            public AppConfiguration(IOptions<ConnectionStrings> options) 
            {
                _options = options;
                _projectManagementConnection = _options.Value.ProjectManagementConnection;
            }
    
            public string GetProjectMgmntConn() => $"{_projectManagementConnection}";
    
        }
    }
    

    Saturday, May 25, 2019 9:41 AM
  • User-2054057000 posted

    As you are starting with the very beginning, I ask you to take some time to understand the DbContext class working as stated in this tutorial - DbContext Class in Entity Framework Core

    Saturday, May 25, 2019 11:55 AM
  • User448619955 posted

    Thanks, I know how to work with DBcontext in .Net core,what I want to know is how to use it in Microsoft Bot Framework,because it's not working in Bot framework.

    thanks By the way, I saw your website and all over the internet it has the same description about how to use DBcontext in .net core,but it's not working in Microsoft Bot framework.

    Saturday, May 25, 2019 12:17 PM
  • User-2054057000 posted

    Thanks, I know how to work with DBcontext in .Net core,what I want to know is how to use it in Microsoft Bot Framework,because it's not working in Bot framework.

    thanks By the way, I saw how to use DBcontext in .net core,but it's not working in Microsoft Bot framework.

    You can also use Dependency Injection feature to get the connection string value in controllers. See How to use Dependency Injection in Entity Framework Core

    Saturday, May 25, 2019 12:59 PM
  • User1120430333 posted

    vahid.ch

    Thanks, I know how to work with DBcontext in .Net core,what I want to know is how to use it in Microsoft Bot Framework,because it's not working in Bot framework.

    thanks By the way, I saw your website and all over the internet it has the same description about how to use DBcontext in .net core,but it's not working in Microsoft Bot framework.

    I showed you how to do it, by using dependency injection in a class constructor.  Dbcontext is a class just like any other class. Whatever a Bot framework is about has to be using the .NET Framework in some manner with classes you created I would think. So learn how to make or change a class to use Dependency Injection provided by the Core IoC

    In the below thread,  I and another poster were in communication about how to get some information from one class/object to another class/object with a .NET Core console program. You have to think outside the box sometimes, becuase no one is going to do it for you.  

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/64aa3ae1-b82e-4b79-be45-f193e1d97876/how-do-i-access-class-propertysettings-in-net-core?forum=csharpgeneral#d2591f47-1e7a-4f0c-9076-9a015f8aecce

    Saturday, May 25, 2019 3:47 PM