Json 序列化器问题。 SQLite 中的空值

问题描述 投票:0回答:1

OnModelCreating
DBContext
方法中,我指定了转换选项:

modelBuilder.Entity<Game>()
    .Property(g => g.Players)
    .HasColumnName("Players")
    .HasColumnType("BLOB")
    .HasConversion(
        v => JsonSerializer.Serialize(v, options),
        s => JsonSerializer.Deserialize<Dictionary<string, Player>>(s, options)!,
        ValueComparer.CreateDefault(typeof(Dictionary<string, Player>), true));

玩家等级

public class Player {
    public string UserID;
    public string UserName;
    public string UserToken;
    public byte InGameOrder;
    public string Team;
    public List<Cards> Hand;
    public Player(string id, string name, string token, int inGameOrder) {
        UserID = id;
        UserName = name;
        UserToken = token;
        InGameOrder = (byte)inGameOrder;
        Team = new string[] { "red", "black" }[inGameOrder % 2];
        Hand = new(8);
    }
    public Player()
    {
        
    }
}

如何添加玩家:

var gameFound = await db.Games.FindAsync(sessionName);

if (gameFound.Players.Count() == 0)
{
    gameFound.Players.Add(userToken, new Player(userID, userName, userToken, 1));
}
else
{
    var prevPlayerInGameOrder = gameFound.Players.Values.Select(p => p.InGameOrder).Max();
    gameFound.Players.Add(userToken, new Player(userID, userToken, userName, prevPlayerInGameOrder + 1));
}

db.Games.Update(gameFound);
int affected = await db.SaveChangesAsync();

但是数据库中我的 Players 字典的值是空的:

{"667440114":{},"181308099":{},"1326342467":{}}

我已经“类型上的反序列化构造函数中的每个参数都必须绑定到反序列化时的对象属性或字段”,因此我在

Player
类中添加了一个无参数构造函数

我想,我需要在序列化参数中指定

Player
的ctor

c# sqlite entity-framework-core
1个回答
0
投票

根据我的经验,当尝试将任何类型的对象(例如玩家类)序列化到数据库或文件时,它需要在类的顶部有一个 [Serialized] 标签,如下所示。

    [Serializable]
    public class Player
    {
        public string UserID;
        public string UserName;
        public string UserToken;
        public byte InGameOrder;
        public string Team;
        public List<Cards> Hand;
        public Player(string id, string name, string token, int inGameOrder)
        {
            UserID = id;
            UserName = name;
            UserToken = token;
            InGameOrder = (byte)inGameOrder;
            Team = new string[] { "red", "black" }[inGameOrder % 2];
            Hand = new(8);
        }
        public Player()
        {

        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.