导航属性问题



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

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

我在 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;

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

这个问题以前已经问过,但解决方案是关于将属性添加到错误中的EntityType[Key]。 但我不需要MoveGameBoard的钥匙.

每个游戏应该只与一个游戏板相关,所以为什么我会有一个游戏板的ID

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

您可能应该将游戏状态序列化为 JSON 文档并存储和检索该文档,而不是将每个类映射到单独的数据库表。 在 EF Core 中,可以使用值转换在单个列中以 JSON 形式存储和检索整个游戏板。 例如,请参阅 https://github.com/Innofactor/EfCoreJsonValueConverter,或者只是在某个实体的字符串属性中自己序列化它。

相关内容

最新更新