实体框架引发错误-无效的列名'Id'。\ r \ n无效的列名'Id'。”

时间:2019-02-25 08:06:57

标签: c# json entity-framework-core

我有以下传入的JSON:

  {
    "SampleNumber": "1605",
    "Status": 2,
    "HasPossibleDuplicate": false,
    "ControlType": 1
  }

这是我的课程:

  public partial class MyMessage: BaseEntity
  {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [JsonProperty("SampleNumber", Required = Required.Always)]
    public string SampleNumber { get; set; }

    [JsonProperty("Status", Required = Required.Always)]
    public string Status { get; set; }

    [JsonProperty("HasPossibleDuplicate", Required = Required.Always)]
    public bool HasPossibleDuplicate { get; set; }

  }

基本实体:

public partial class BaseEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? Created { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? Updated { get; set; }
}

这是我的代码,用于解析传入的JSON并将其存储在相应的表中。

    MyMessage message = DeserializeObject.FromJson(jsondata);
    if (message != null)
    {
     using (var transaction = myContext.Database.BeginTransaction())
     {
       myContext.MyMessage.Add(message);//error comes here
       myContext.SaveChanges();
       transaction.Commit();
     }
    }

我收到以下异常:

  

“无效的列名'HasPossibleDuplicate'。\ r \ n无效的列名'Id'。\ r \ n无效的列名'Id'。”

1 个答案:

答案 0 :(得分:1)

JSON中缺少

属性 Id ,并且在数据库实体类中是必需的。您可以为json数据创建一个单独的类(DTO),然后将JSON反序列化为新创建的类。

public class MessageDto
{
    public string SampleNumber { get; set; }     
    public string Status { get; set; }     
    public bool HasPossibleDuplicate { get; set; }
    public int ControlType { get; set; }
}
MessageDto dto = JsonConvert.DeserializeObject<MessageDto>(jsonData);

if (dto != null) {
    MyMessage message = new MyMessage();
    message.SampleNumber = dto.SampleNumber;
    message.Status = dto.Status;
    message.HasPossibleDuplicate = dto.HasPossibleDuplicate;
    message.ControlType = dto.ControlType;

    using (var transaction = myContext.Database.BeginTransaction())
     {
       myContext.MyMessage.Add(message);//error comes here
       myContext.SaveChanges();
       transaction.Commit();
     }
}