EF返回旧数据

马修

会员
已加入
2020年8月15日
留言内容
23
编程经验
Beginner
嗨,大家好,

我正在使用EF和sqlite制作一个非常简单的CRUD控制台应用程序。
我有3个领域模型类,分别是:玩家,锦标赛和锦标赛报名

Player:
    public class Player
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        public string FullName => $"{FirstName} {LastName}";

        public ICollection<TournamentEnrollment> TournamentEnrollments { get; set; }
    }

Tournament:
    public class Tournament
    {
        [Key]
        public int Id { get; set; }
        
        [Required]
        public string Name { get; set; }

        public ICollection<TournamentEnrollment> Enrollments { get; set; }
    }

比赛报名:
    public class TournamentEnrollment
    {
        [Key]
        public Tournament Tournament { get; set; }
        [Key]
        public Player Player { get; set; }
    }

在DAL层中,我用几种方法创建了一个存储库。

DAL:
public class Repository : IRepository
    {
        private readonly TmDbContext _context;

        public Repository()
        {
            _context = new TmDbContext();
        }

        public Repository(TmDbContext context)
        {
            _context = context;
        }
        
        public Player ReadPlayer(int id)
        {
            return _context.Players.Find(id);
        }

        public Tournament ReadTournament(int id)
        {
            return _context.Tournaments.Find(id);
        }

        public IEnumerable<Tournament> ReadAllTournamentsWithParticipants()
        {
            return _context.Tournaments
                .Include(t => t.Enrollments)
                    .ThenInclude(te => te.Player);
        }

        public TournamentEnrollment ReadTournamentEnrollment(int tournamentId, int playerId)
        {
            return _context.TournamentEnrollments.Find(tournamentId, playerId);
        }

        public IEnumerable<TournamentEnrollment> ReadAllTournamentEnrollments()
        {
            return _context.TournamentEnrollments
                .Include(te => te.Player)
                .Include(te => te.Tournament);
        }

        public void DeleteTournamentEnrollment(int tournamentId, int playerId)
        {
            TournamentEnrollment tournamentEnrollment = ReadTournamentEnrollment(tournamentId, playerId);
            _context.TournamentEnrollments.Remove(tournamentEnrollment);
            _context.SaveChanges();
        }
    }

还有我的DbContext

DbContext:
 public class TmDbContext : DbContext
    {
        public DbSet<Player> Players { get; set; }
        public DbSet<Tournament> Tournaments { get; set; }
        public DbSet<TournamentEnrollment> TournamentEnrollments { get; set; }

        public TmDbContext()
        {
            TmDbInitializer.Initialize(this, true);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseSqlite("data source = tm.db")
                .UseLoggerFactory(LoggerFactory.Create(lb => lb.AddDebug()));
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TournamentEnrollment>()
                .HasOne(te => te.Tournament)
                .WithMany(t => t.Enrollments)
                .HasForeignKey("TournamentId")
                .IsRequired();
            modelBuilder.Entity<TournamentEnrollment>()
                .HasOne(te => te.Player)
                .WithMany(p => p.TournamentEnrollments)
                .HasForeignKey("PlayerId")
                .IsRequired();
            modelBuilder.Entity<TournamentEnrollment>()
                .HasKey("TournamentId","PlayerId");
        }
    }

最后,您可以找到控制台应用程序的Program.cs文件

Program:
    class Program
    {
        private static IRepository _repo = new Repository();
        private static bool _exit;

        static void Main(string[] args)
        {
            while (!_exit)
            {
                try
                {
                    ShowMenu();
                    MakeChoice();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }

        private static void ShowMenu()
        {
            Console.WriteLine("1) Show all tournaments");
            Console.WriteLine("2) Remove tournament enrollment");
            Console.WriteLine("3) Show all tournament enrollments");
            Console.WriteLine("0) Exit");
        }

        private static void MakeChoice()
        {
            Console.Write("=>: ");

            if (!Int32.TryParse(Console.ReadLine(), out int choice))
            {
                Console.WriteLine("\nPlease enter a numeric value!\n");
            }
            else
            {
                switch (choice)
                {
                    case 1:
                        ShowAllTournaments();
                        break;
                    case 2:
                        RemoveTournamentEnrollment();
                        break;
                    case 3:
                        ShowAllTournamentEnrollments();
                        break;
                    case 0:
                        _exit = true;
                        break;
                }
            }
        }

        private static void ShowAllTournaments()
        {
            Console.WriteLine();

            foreach (var t in _repo.ReadAllTournamentsWithParticipants())
            {
                Console.WriteLine($"[{t.Id}] {t.Name}");

                foreach (var te in t.Enrollments)
                {
                    Console.WriteLine($"\t- [{te.Player.Id}] {te.Player.FullName}");
                }
            }

            Console.WriteLine();
        }

        private static void ShowAllTournamentEnrollments()
        {
            Console.WriteLine();

            foreach (var te in _repo.ReadAllTournamentEnrollments())
            {
                Console.WriteLine($"Tournament = {te.Tournament.Name} | Player = {te.Player.FullName}");
            }

            Console.WriteLine();
        }

        private static void RemoveTournamentEnrollment()
        {
            Console.Write("\nTournamentId: ");
            int tournamentId = Int32.Parse(Console.ReadLine());

            Console.Write("PlayerId: ");
            int playerId = Int32.Parse(Console.ReadLine());

            Console.WriteLine();

            _repo.DeleteTournamentEnrollment(tournamentId, playerId);
        }
    }

当我删除TournamentEnrollment记录(使用控制台应用程序中的选项2),然后又要求所有参与者与其参加比赛(使用控制台应用程序中的选项1)时,该注册不再如预期的那样可见。
现在出现了我遇到的问题。在控制台应用程序运行期间,我使用SQLite Studio(用于浏览和编辑sqlite文件的桌面工具)手动删除了TournEnrollment记录,并且在提交后,我要求参与者参加所有比赛(使用控制台应用程序中的选项1) ,注册仍然可见。现在我知道它与桌面工具无关,因为当我要求显示所有TournamentEnrollments(使用控制台应用程序中的选项3)时,它减少了一个,所以我很困惑为什么一个查询显示正确的结果而一个查询显示旧的结果结果。与缓存或...有关吗?

我希望我能够概述问题,因为我的英语不太好 :) .

非常感谢你!
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,500
地点
弗吉尼亚州切萨皮克
编程经验
10+
最佳 底部