导航属性问题

时间:2019-08-10 08:51:13

标签: c# entity-framework ef-code-first ef-migrations code-first

我已经用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类具有以下属性:

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的密钥。

1 个答案:

答案 0 :(得分:1)

  

每个游戏应该只与一个GameBoard相关,所以为什么我要为GameBoard设置一个ID

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

您可能应该将游戏状态序列化为JSON文档并进行存储和检索,而不是将每个类映射到单独的数据库表。在EF Core中,您可以使用Value Conversion来将整个GameBoard作为JSON存储和检索在单个列中。参见https://github.com/Innofactor/EfCoreJsonValueConverter,或者自己在某个实体的字符串属性中对其进行序列化。

相关问题