导航 属性 问题

Navigation property issue

我在 C# 中创建了一个 ChessLibrary 并在 WinForms 项目上对其进行了测试。

现在,我正在尝试使用 ASP.NET MVC 创建一个网站,EF 代码优先使用此库。

我在我的 asp.net mvc 项目中创建了一个 Game 模型,具有以下属性:

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; }

    }
}

当我尝试 Add-Migration 时,出现以下错误:

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.

我的 GameBoard class 具有以下属性:

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;

我不确定是否有简单的解决方案,或者我从一开始就有设计问题?

这个问题之前有人问过,但是解决方案是在错误中将[Key]属性添加到EntityType。但我不需要 MoveGameBoard.

的密钥

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

这是关键问题。在内存中,对象不需要 ID。但是如果你想将对象保存到数据库并稍后检索它,它必须有一个键 属性.

您可能应该将游戏状态序列化为 JSON 文档并存储和检索它,而不是将每个 class 映射到单独的数据库 table。在 EF Core 中,您可以使用 Value Conversion to store and retrieve the entire GameBoard in a single column as JSON. See eg https://github.com/Innofactor/EfCoreJsonValueConverter,或者自己将其序列化为某个实体的字符串 属性。