数据库在同时使用两个应用程序时未能刷新。

huangapple go评论58阅读模式
英文:

Database not getting refreshed when using 2 apps at the same time

问题

I'm sorry, but it seems that the content you provided contains code that should not be translated. If you have specific text that you would like me to translate from English to Chinese, please provide that text separately, and I'll be happy to assist you with the translation.

英文:

I'm posting a video of the problem for clarity because I'm not sure that I will be able to explain it in words: https://www.youtube.com/watch?v=vCDG91zbgoI
Basically, I have 2 identical apps connected to the same database. I want to run them both at the same time.

When I try to get the information from the DB only from one app - no problem. But when I run both, I change the information with the command "Change" in one of the apps. Then use "Show" in the other - the information I get is outdated(the one before I used "change" on the first app). The database gets updated, but the second app doesn't get the latest information from the DB. Restarting the 2nd app and then using "Show" returns the newest information, but that won't help me. The Player player = context.Players.First(p => p.ID == 1); inside the while(true) should mean that the information taken is always the newest, but I guess not.
Here is the whole code:

TTTContext context = new TTTContext();
while(true)
{
        string command = Console.ReadLine();
	Player player = context.Players.First(p => p.ID == 1);
	if (command == "Show")
	{
            Console.WriteLine(player.Name);
        }
	else if (command == "Change")
	{
	     string name = Console.ReadLine();
	     player.Name = name;
	     context.Players.Update(player);
	     context.SaveChanges();
	}
}

Here is my TTTContext class:

public class TTTContext: DbContext
	{
		public DbSet<Player> Players { get; set; }

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseMySQL("Server=localhost;Database=Test;Uid=root;Pwd=Martin1234;");

			base.OnConfiguring(optionsBuilder);
		}
	}

答案1

得分: 0

Replacing context.Players.First(p => p.ID == 1) with context.Players.AsNoTracking().First(p => p.ID == 1) fixes the issue.

英文:

Replacing context.Players.First(p => p.ID == 1) with context.Players.AsNoTracking().First(p => p.ID == 1) fixes the issue.

huangapple
  • 本文由 发表于 2023年5月10日 22:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定