Search code examples
c#asp.net.netasp.net-mvctopshelf

How to use MYSQL DbContext of ASP.NET MVC from console application using ASP.NET MVC project reference


I am trying to write a Windows service from .NET console application which performs the operation of posting the data in the MySQL database. I am trying to use the DbContext class from ASP.NET project but when I run the console application the data does not get posted. I am using Topshelf dependency to create Windows service and make debugging easier.

My console app code looks like this:

public class UpdateReceivePost
{
        private readonly Timer timer;// To establish time for service

        public UpdateReceivePost()
        {
            timer = new Timer(1000) { AutoReset = true }; // the service will start in one minute 
            timer.Elapsed += TimerElapsed;//calls a timeelapsed mehodd
        }

        protected IDbFactory DbFactory { get; private set; }

        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            UserDbContext dbContext = new UserDbContext();

            ReceivePost receivePost = new ReceivePost()
            {
                Status = "pending"
            };

            dbContext.receivePosts.Add(receivePost);
            dbContext.SaveChanges();

            // string[] lines = new string[] { DateTime.Now.ToString() };
            // File.AppendAllLines(@"F:\nepal.txt", lines);
        }

        public void Start()
        {
            timer.Start();//start the timer
        }

        public void Stop()
        {
            timer.Stop(); //stops the timer
        }
} 

Solution

  • You should wrap your dbContext class within a using statement to dispose it off once you are done posting to the db.

    The lifetime of the context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block. When you use using, the compiler automatically creates a try/finally block and calls dispose in the finally block.

    Install-Package MySQL.Data -Version 6.9.9
    Install-Package MySql.Data.Entity -Version 6.9.10
    

    Try to reinstall the packages with these versions and see if the error disappears.

    private void TimerElapsed(object sender, ElapsedEventArgs e)
     {
        ReceivePost receivePost = new ReceivePost()
        {
           Status = "pending"
        };
    
        using(UserDbContext dbContext = new UserDbContext())
        {
            dbContext.receivePosts.Add(receivePost);
            dbContext.SaveChanges();
        }
    
        // string[] lines = new string[] { DateTime.Now.ToString() };
       // File.AppendAllLines(@"F:\nepal.txt", lines);
    }