Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 854
Praveen R Avatar asked Nov 23 '17 12:11

Praveen R


People also ask

Can you use JSON in C?

Parsing JSON in C using microjson Developed originally for server-browser communication, the use of JSON has since expanded into a universal data interchange format. This tutorial will provide a simple introduction to parsing JSON strings in the C programming language using the microjson library.

How is JSON data used?

JSON data types and examples It is often used for serializing structured data and exchanging it over a network, typically between a server and web applications.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.


2 Answers

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!

like image 73
facundofarias Avatar answered Oct 23 '22 03:10

facundofarias


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);
}
like image 31
Hey24sheep Avatar answered Oct 23 '22 05:10

Hey24sheep