Bhushan Dhage
Bhushan Dhage

Reputation: 73

ServiceStack ORMLite How to fparse JSON data in Query

I have the following model structure.

public class Inforamation 
{ 
  public Guid Id { get; set; }

  public string Name { get; set; }

  public InfoMetadata Metadata { get; set; }
}

public class InfoMetadata 
{ 
  // Bike Info

  public string BikeName { get; set; }
  public string ModelNumber { get; set; }

  // House Info
  public string HouseName { get; set; }
  public string HouseNumber { get; set; }

}

Request DTO

public class RequestDto
{ 
public string Query { get; set; }
}

//Service

 public void Get(RequestDto request)
    {
      var query = Db.From<Inforamation>();
    
      query = query.And<Inforamation>(v => v.Name == query || v.InfoMetadata.BikeName == query);

var result = Db.select(query);
    
    }

My database table structure is like:

-----------------------------------------------------------------
|   Id      |   Name    |Metadata                               |
|           |           |                                       |
|      1    |  Bhushan  |{"houseName": 'ABC', "BikeName": "VC"} |
-----------------------------------------------------------------

//Error getting on Db.Select(query);

The multi-part identifier "InfoMetadata .BikeName " could not be bound.'

Can some one please told me how to parse that type of data.

Upvotes: 2

Views: 511

Answers (1)

mythz
mythz

Reputation: 143319

Complex Types are blobbed by default in OrmLite using their configured Complex Type Serializer which you typically can't perform server side queries on, so you shouldn't blob fields you want to be able to query with SQL as they can only be inspected after the resultsets are materialized in C#.

If you're using PostgreSQL you can use its rich JSON Data Type by annotating Complex Type properties with [PgSqlJson] or [PgSqlJsonB] attributes, e.g:

public class TableJson
{
    public int Id { get; set; }

    [PgSqlJson]
    public ComplexType ComplexTypeJson { get; set; }

    [PgSqlJsonB]
    public ComplexType ComplexTypeJsonb { get; set; }
}

db.Insert(new TableJson
{
    Id = 1,
    ComplexTypeJson = new ComplexType {
        Id = 2, SubType = new SubType { Name = "JSON" }
    },
    ComplexTypeJsonb = new ComplexType {
        Id = 3, SubType = new SubType { Name = "JSONB" }
    },
});

Where they can then be queried on the server with PostgreSQL's JSON SQL Syntax and functions:

var result = db.Single<TableJson>("table_json->'SubType'->>'Name' = 'JSON'");

Otherwise you will only be able to query the results on the client using LINQ in C# after executing the Server query, e.g:

var results = Db.Select(Db.From<Information>().Where(x => x.Name == query));
var filteredResults = results.Where(x => x.InfoMetadata.BikeName == query).ToList();

Upvotes: 1

Related Questions