How to use Json data type in C# Entity Framework model?

时光怂恿深爱的人放手 提交于 2021-01-23 01:46:53

问题


model.cs

[Column(TypeName = "json")]
    public string application_role { get; set; }

Its MySQL, data type of particular column is json, and how to add it in a model class. I tried with DataAnnotations but getting error as

The specified type member 'application_role' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Linq Query to get data

context.sc_employee_details
                    .Where(e => e.user_name.Equals(userName))
                    .Select(o => o.application_role).SingleOrDefault();

回答1:


It might be a bit late, but EF on MySQL supports JSON format, here is announcement. Basically, you have to define an attribute like this one:

public JsonObject<string[]> Tags { get; set; } // Json storage

hope it helps!




回答2:


You will do something like this

   private string _application_role;
   public string application_role 
   { 
       get{
            return JsonConvert.DeserializeObject<string>(_application_role)
         } 
       set{
           _application_role = JsonConvert.SerializeObject(value);
         } 
   }

Or if you do not want to edit your model then you could do something like this

var myRole = context.sc_employee_details
                    .Where(e => e.user_name.Equals(userName))
                    .Select(o => o.application_role).SingleOrDefault();

if(myRole != null){
  var desRole = JsonConvert.DeserializeObject<string>(myRole);
}


来源:https://stackoverflow.com/questions/47455701/how-to-use-json-data-type-in-c-sharp-entity-framework-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!