Youssef13
Youssef13

Reputation: 4944

Navigation property issue

I've created a ChessLibrary in C# and tested it on a WinForms project.

Now, I'm trying to make a website using ASP.NET MVC, EF code-first to consume this library.

I've created a Game model in my asp.net mvc project with the following properties:

using ChessLibrary;

namespace ChessWebsite.Models
{
    public class Game
    {
        public int Id { get; set; }
        public ApplicationUser WhitePlayer { get; set; }
        public ApplicationUser BlackPlayer { get; set; }
        public GameBoard GameBoard { get; set; }

    }
}

when I try to Add-Migration, I get the following error:

One or more validation errors were detected during model generation:

ChessWebsite.Models.GameBoard: : EntityType 'GameBoard' has no key defined. Define the key for this EntityType.
ChessWebsite.Models.Move: : EntityType 'Move' has no key defined. Define the key for this EntityType.
GameBoards: EntityType: EntitySet 'GameBoards' is based on type 'GameBoard' that has no keys defined.
Moves: EntityType: EntitySet 'Moves' is based on type 'Move' that has no keys defined.

My GameBoard class has the following properties:

public List<Move> Moves { get; set; }
public Piece[,] Board { get; set; }

public GameState GameState { get; private set; }
public bool CanWhiteCastleKingSide { get; private set; } = true;
public bool CanWhiteCastleQueenSide { get; private set; } = true;
public bool CanBlackCastleKingSide { get; private set; } = true;
public bool CanBlackCastleQueenSide { get; private set; } = true;

I'm not sure if there is a simple solution, or I've a design problem from the beginning ?

This question has been asked before, but the solutions was about adding [Key] attribute to EntityType in the error. but I don't need a key for Move or GameBoard.

Upvotes: 0

Views: 255

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88852

each Game should be related to only one GameBoard so why I would have an Id for GameBoard

This is the key question. In memory an object doesn't need an ID. But if you want to save the object to a database and retrieve it later it has to have a key property.

You should probably serialize the game state to a JSON document and store and retrieve that, instead of mapping each class to a separate database table. In EF Core you can use a Value Conversion to store and retrieve the entire GameBoard in a single column as JSON. See eg https://github.com/Innofactor/EfCoreJsonValueConverter, or just serialize it yourself in string property of some entity.

Upvotes: 1

Related Questions