Aeseir
Aeseir

Reputation: 8414

EF Core - Entity with Dynamic Properties

I am trying to figure out what is the best way to deal with dynamic data, and store it in db.

The scenario for example, imagine a car, there are mandatory fields we want to capture such as used, model, cost, but then there are all the other aspects that make up the car and its uniqueness we want to capture that varies, such as roof type (glass, cloth, or metal), or headlights (neon, led etc.) that one car might have or not.

What is the best way to create a entity to capture this dynamic data.

Currently I just stored everything in a single JSON string

public class Car
{
    public String Model {get;set;}
    public bool IsUsed {get;set;}
    public float Cost {get;set;}
    public String? Features {get;set;} // this is a JSON string of all features 
}

This worked until recently, now i want to be able to query this list of features that may have 0...N features in Key:Value format.

What is the more effective way to handle this challenge?

Upvotes: 0

Views: 1887

Answers (2)

novaXire
novaXire

Reputation: 136

With a PostgreSQL Database, add this :

[Column(TypeName = "jsonb")]
public string Features {get;set;}

And use Serialization and Deserialization when you need to access to values :

JsonSerializer.Deserialize<Dictionary<string,string>>(car.Features);

Upvotes: 1

Shailen Sukul
Shailen Sukul

Reputation: 510

  1. You can use a database which supports storing and querying on JSON data, ex PostGreSQL

  2. You can then use the suggested pattern for unstable data (https://www.npgsql.org/efcore/mapping/json.html#jsondocument-dom-mapping)

public class SomeEntity : IDisposable
{
    public int Id { get; set; }
    public JsonDocument Customer { get; set; }

    public void Dispose() => Customer?.Dispose();
}

The query would then look like this:

// .Net
EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)

var searchedCustomers = _context.Customers.Where(p => 
EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", p.Customer);

Just remember to index properly.

Upvotes: 1

Related Questions