1

I have a list of Columns that i generate in the following code snippets:


public Match CreateColumn(Match match)
        {
            match.Columns = new List<Column>();
            match.Moves = new List<Move>();
            for (int i = 0; i < 7; i++)
            {
                match.Columns.Add(new Column());
            }
            return match;
        }

That is called in the create method below:

public ActionResult Create(Match match)
        {
            match.State = State.InPartenza;
            match.Data = DateTime.UtcNow.ToString("dd-MM-yyyy");
            match.NextTurnPlayer = match.SetNextTurnPlayer();
            match.UsernamePlayer1 = User.Identity.GetUserName();
            if (!ModelState.IsValid || db.Matches.Find(match.Name) != null || string.IsNullOrWhiteSpace(match.Name))
            {
                ModelState.AddModelError("", "This name is already associated to another game");
                return View(match);
            }
            match = match.CreateColumn(match);
            db.Matches.Add(match);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

The problem is that Colums is alway null and never equals to 7, why?

UPDATE

I get the error int he first if condition

public bool PlayerHasOccupied(Match match, int j, int i, int player)
        {
            if (match.Columns.Count > 0 && match.Columns[j].Cells != null && i <= match.Columns[j].Cells.Count)
            {
                return match.Columns[j].Cells[i].Value == player;
            }
            else
            {
                return false;
            }
        }

The error:

System.NullReferenceException: 'Object reference not set to an instance of an object.' Connect4.Models.Match.Columns.get returned null.

UPDATE 2

Match

        public List<Column> Columns { get; set; }
        [Key]
        [Required]
        public string Name { get; set; }
        public string Data { get; set; }
        [Display(Name = "Next turn player")]
        public NextTurnPlayer NextTurnPlayer { get; set; }
        public State State { get; set; }
        public string UsernamePlayer1 { get; set; }
        public string UsernamePlayer2 { get; set; }
        public string Winner { get; set; }/
        public List<Move> Moves { get; set; }

        public int CanWin { get; set; }

Column

public class Column
    {

        public int Id { get; set; }
        public List<Cell> Cells { get; set; }
        public bool IsFull()
        {
            return Cells.Count == 6;
        }
    }

Cell

public class Cell
    {
        [Key]
        public int Value { get; set; }
        
        public bool IsEmpty(int value)
        {
            return !Convert.ToBoolean(value);
        }
    }

UPDATE 3

public class ManageViewModels : DbContext
    {
        public DbSet<Match> Matches { get; set; }
    }

0 Answers0