简体   繁体   English

如何使用实体框架代码优先将 Boolean 数组绑定到 C# model?

[英]How do I bind a Boolean array to a C# model using Entity Framework Code First?

I am trying to serialize a JSON response into a Entity Framework Code First model.我正在尝试将 JSON 响应序列化为实体框架代码优先 model。

The payload is as follows:有效载荷如下:

[{
 "_cs_regimen":"3_per_week",
 "_cs_account_email":"my@email.com",
 "_cs_results":[true,true,false], <<< ### The property in question ###
 "_cs_distance":[101018.52287999999,460594.25279999996],
 "_cs_joined_team_time":"2022-06-11T10:36:15.840649Z",
 "_cs_account_lastName":...

My model is as follows:我的 model 如下:

public class LeaderboardData
{
    [Key]
    public int LeaderboardId { get; set; }

    [DefaultValue(1)]
    public int Week { get; set; }
    ......

    public virtual LeaderboardRideResult _cs_results { get; set; } < I want to bind the boolean array into this property.
}

LeaderboardRideResult looks like this: LeaderboardRideResult 看起来像这样:

public class LeaderboardRideResult
{
    [Key]
    public int Id { get; set; }

    public string tag { get; set; }

    public List<bool> contents { get; set; }

    [ForeignKey("LeaderboardData")]
    public int LeaderboardDataId { get; set; }
}

And I have a mapping to bind the array back to a boolean list here:我有一个映射来将数组绑定回 boolean 列表:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<RiderOptIn>()
                .HasIndex(entity => new { entity._email, entity._username })
                .IsUnique();

            modelBuilder.Entity<LeaderboardRideResult>().Property(p => p.contents)
             .HasConversion(
                 v => JsonConvert.SerializeObject(v),
                 v => JsonConvert.DeserializeObject<List<bool>>(v));
                }

Deserialization code (Newtonsoft):反序列化代码(Newtonsoft):

List<LeaderboardData> myDeserializedClass = JsonConvert.DeserializeObject<List<LeaderboardData>>(result); (result = the JSON above)

I'm getting this back:我要回来了:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'KiltedRiders.Models.LeaderboardRideResult' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '[0]._cs_results', line 1, position 90.'

Any hints on this would be apprecaited.对此的任何提示将不胜感激。

Your C# model is not matching the incoming json type.您的 C# 模型与传入的 json 类型不匹配。

public virtual LeaderboardRideResult _cs_results { get; set; } public virtual LeaderboardRideResult _cs_results { get; set; } should be like public virtual LeaderboardRideResult _cs_results { get; set; }应该像

public virtual bool[] _cs_results { get; set; }

or或者

public virtual List<bool> _cs_results { get; set; }

Add another new property in your model for retrieve data:在 model 中添加另一个新属性以检索数据:

    [NotMapped]
    [JsonProperty(PropertyName = "_cs_results")]
    public virtual List<bool> CsResult { get; set; }

Finally LeaderboardData model look like:最后LeaderboardData model 看起来像:

public class LeaderboardData
{

    public int LeaderboardId { get; set; }

    [DefaultValue(1)]
    public int Week { get; set; }
    [NotMapped]
    [JsonProperty(PropertyName = "_cs_results")]
    public virtual List<bool> CsResult { get; set; }
    public virtual LeaderboardRideResult _cs_results { get; set; }
}

As vaibhavit80 explained above the type you are trying to deserialize into is wrong.正如上面 vaibhavit80 解释的那样,您尝试反序列化的类型是错误的。 I suspect you will kick yourself when the penny drops:-)我怀疑当便士掉下来时你会踢自己:-)

I've stripped it right back, try running this and hopefully you will see the issue.我已经把它去掉了,试着运行它,希望你能看到这个问题。

internal class Program
{

    public class LeaderboardRideResult
    {
        public List<bool> contents { get; set; }
    }

    public class LeaderboardData
    {
        public virtual LeaderboardRideResult _cs_results { get; set; } //  < I want to bind the boolean array into this property.
    }

    public class LeaderboardData_2
    {
        public virtual List<bool> _cs_results { get; set; } //  < I want to bind the boolean array into this property.
    }


    static void Main(string[] args)
    {
        var json = "{ \"_cs_results\":[true,true,false] }"; // <<< ### The property in question ###

        try
        {
            var myDeserializedClass = JsonConvert.DeserializeObject<LeaderboardData>(json);
        }
        catch (Exception x)
        {
            System.Console.WriteLine(x);
        }

        var myDeserializedClass2 = JsonConvert.DeserializeObject<LeaderboardData_2>(json);
    }
}

The exception caused by the first deserialization attempt is the same as the one you mention:第一次反序列化尝试引起的异常与您提到的相同:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'DeserTest.Program+LeaderboardRideResult' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'DeserTest.Program+LeaderboardRideResult' because the type requires a JSON object (eg {"name":"value"})正确反序列化。 To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array.要修复此错误,请将 JSON 更改为 JSON object(例如 {"name":"value"})或将实现的反序列化类型接口更改为数组或数组从 JSON 阵列反序列化。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。 Path '_cs_results', line 1, position 17. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)....路径'_cs_results',第 1 行,position 17. 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader 阅读器,类型 objectType,JsonContract 合同)。

The fact that it's an EF model is nothing to do with it.它是 EF model 的事实与它无关。 Neither is the fact that the property is virtual.财产是虚拟的也不是事实。

The issue is you are trying to serialize a bool array into a class.问题是您正在尝试将 bool 数组序列化为 class。

Your json should be parseable and can be converted as an object.您的 json 应该是可解析的,并且可以转换为 object。 In case of your model structure, it is not.如果是您的 model 结构,则不是。 I can't see the relationship on your sample models, but you can try creating an entity for your Content property, like this:我看不到您的示例模型上的关系,但您可以尝试为您的 Content 属性创建一个实体,如下所示:

public class Content 
{
    public int Id { get;set; }
    public bool Value { get;set; }

    [ForeignKey("LeaderboardRideResult")]
    public int LeaderboardRideResultId { get; set; }

    public virtual LeaderboardRideResult LeaderboardRideResult { get;set; }
}

And here, I updated minor name on your 2 existing models:在这里,我更新了您现有 2 个模型的次要名称:

public class LeaderboardData
{
    [Key]
    public int LeaderboardId { get; set; }

    [DefaultValue(1)]
    public int Week { get; set; }
    ......

    public virtual LeaderboardRideResult LeaderboardRideResult { get; set; }
}

public class LeaderboardRideResult
{
    [Key]
    public int LeaderboardRideResultId { get; set; }

    public string Tag { get; set; }

    ...

    [ForeignKey("LeaderboardData")]
    public int LeaderboardDataId { get; set; }

    public ICollection<Content> Contents { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用实体框架代码优先将 C# int 映射到 SqlServer tinyint? - How do I map a C# int to a SqlServer tinyint using Entity Framework Code First? c#WPF首先使用LINQ将组合框绑定到实体框架代码中的TPH - c# WPF bind combobox to TPH in Entity Framework code first using LINQ C#实体框架(代码优先),在模型上实现CRUD操作 - C# Entity Framework (Code first), Implementing CRUD Operations on Model 如何使用C#-WPF-Entity-Framework Code First应用程序创建数据库备份? - How do I create database backups using C#-WPF-Entity-Framework Code First application? 如何在MVC 4中使用Entity Framework从C#代码部分使用SQL函数 - How do I use a SQL function from C# code section using Entity Framework in MVC 4 EF例外,如何首先在C#和实体框架代码中为地址建模 - EF exception, how to model addresses in c# and entity framework code first 如何从C#Entity Framework Code First Model获取mysql char列类型 - How to get mysql char column type from C# Entity Framework Code First Model C# 实体框架代码优先 - 如何仅使用该外键的 id 添加带有外键的行? - C# Entity Framework Code-First- How do you add a row with foreign key using just the id of that foreign key? 如何使用实体框架C#将两个表绑定到Datagridview - How to bind two tables to Datagridview using entity framework C# 如何将主键标识列添加到实体框架代码首先生成的模型 - How do I add a Primary Key identity column to Entity Framework Code First generated Model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM