System.Text.Json.JsonException: JSON 值无法转换为 Entities.UserCard。路径:$[0].Cards

System.Text.Json.JsonException: The JSON value could not be converted to Entities.UserCard. Path: $[0].Cards

这是我的程序 class 将要开始迁移的地方

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        using var scope = host.Services.CreateScope();
        var services = scope.ServiceProvider;
        try{
            var context = services.GetRequiredService<DataContext>();
            await context.Database.MigrateAsync();
            await Seed.SeedUsers(context);
        }catch(Exception ex){
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex,"An error occurred during migration");
        }

        await host.RunAsync();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

这是我的主要class

public class AppUser
{
    public int Id { get; set; }
    [StringLength(20)]

    public string UserName { get; set; }

    public byte[] PasswordHash { get; set; }

    public byte[] PasswordSalt { get; set; }

    public DateTime DateOfBirth { get; set; }

    public DateTime Created { get; set; }=DateTime.Now;

    public DateTime LastActive { get; set; }=DateTime.Now;

    public string Gender { get; set; }
    public string City { get; set; }
    public string Country { get; set; }

    public ICollection<Photo> Photos { get; set; }

    public UserCard Cards { get; set; }

    public int GetAge(){
        return DateOfBirth.CalculateAge();
    }
}

这是我想在数据库中与 AppUser 链接的 UserCard

[Table("Cards")]
public class UserCard
{
     public int Id { get; set; }
    public string Code { get; set; }
    public string Status { get; set; }
    public string Type { get; set; }

    public AppUser AppUser{ get; set; }
    public int AppUserId { get; set; }
}

这是我的种子函数的样子

public class Seed
{
    public static async Task SeedUsers(DataContext context){
        if(await context.Users.AnyAsync()) return;

        var userData=await System.IO.File.ReadAllTextAsync("Data/UserSeedData.json");
        var users=JsonSerializer.Deserialize<List<AppUser>>(userData);
        foreach (var user in users)
        {
            using var hmac=new HMACSHA512();
            user.UserName = user.UserName.ToLower();
            user.PasswordHash=hmac.ComputeHash(Encoding.UTF8.GetBytes("admin"));
            user.PasswordSalt=hmac.Key;
            context.Users.Add(user);
        }

        await context.SaveChangesAsync();
    }

这是我想放入 database.Here 的数据,我还有另一张 class 照片,这就是它在那里的原因

[
{
    "UserName": "Tami",
    "Gender": "female",
    "DateOfBirth": "1995-09-28",
    "Created": "2020-05-01",
    "LastActive": "2020-05-29",
    "City": "Haring",
    "Country": "San Marino",
    "Photos": [
        {
            "Url": "https://randomuser.me/api/portraits/women/94.jpg",
            "IsMain": true
        }
    ],
    "Cards": [
        {
            "Code": "123123543",
            "Status": "notActive",
            "Type": "default"
        }
    ]
}
]

当我输入:dotnet watch 运行 我的数据库将使用正确的链接正确地创建表但是当种子发生时我得到这个错误

  fail: API.Program[0]
  An error occurred during migration
  System.Text.Json.JsonException: The JSON value could not be converted to Entities.UserCard. Path: $[0].Cards | LineNumber: 15 | BytePositionInLine: 18.
     at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
     at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
     at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
     at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
     at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
     at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
     at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
     at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
     at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
     at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
     at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
     at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
     at API.Data.Seed.SeedUsers(DataContext context) in C:\Users\Alejandro\Desktop\ProjectApp\API\Data\Seed.cs:line 19
     at API.Program.Main(String[] args) in C:\Users\Alejandro\Desktop\ProjectApp\API\Program.cs:line 24

我找到问题了

  public ICollection<Photo> Photos { get; set; }
    public UserCard Cards { get; set; }

我只需要将 ICollection 放到 Cards 道具上,但我需要帮助来解决这个问题。现在使用 ICollection 时,关系是一对多的,但是对于卡片,我希望关系是 1 对 1 我需要做什么在这种情况下?

对于 1 对 1 关系,您可以像这样更改 json 结构;

[
{
    ...
    "Cards": {
            "Code": "123123543",
            "Status": "notActive",
            "Type": "default"
        }
    ...

}
]

请注意 Cards 属性 现在是一个对象,而不是数组。