Skip to content
Maxim Chistyakov edited this page Jul 15, 2023 · 4 revisions

Here is a detailed usage example:

//Specify using
using Microsoft.EntityFrameworkCore;
using JsonProperty.EFCore;

//Setup serialization setings
Settings.JsonSettings.StrictTypeSerialization = true;

//Create array of products
List<Product> products = new()
{
    new() {Name="Phone",Price=500.95m,Amount=21,Parameters={
            VirtualDictionary = new Dictionary<string,object>() {
                {"Camera",13.5 },{"OS","Android" },{"Screen","1080x900"},{"Storage",32}
            }
        }
    },
    new() {Name="Car",Price=100000m,Amount=3,Parameters={
            VirtualDictionary = new Dictionary<string,object>() {
                {"MaxSpeed",300},{ "Engine capacity",6},{"ElectroCar",false}
            }
        }
    }
};

//Create single product
var product = new Product() { Name = "Bag" };
product.Price = 399.99m;
product.Amount = 7;

//AddRange
product.Parameters.AddRange(new Dictionary<string, object>() {
    //You can add values ​​of different types if the base type is object 
    { "Volume", 5 }, { "Color", "Red" }
});

//Add
product.Parameters.Add("Matherial", "Leather");

//Edit
product.Parameters.Edit(params=>{
    params["Color"] = "Blue";
    return params;
});

//Get collection
var paramsDictionary = product.Parameters.Deserialize();

using (var db = new DataContext())
{
    //Add products
    db.Goods.AddRange(products);
    //Add product
    db.Goods.Add(product);
    //Save to DB
    db.SaveChanges();
}

//Entity model
public class Product
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public decimal? Price { get; set; }
    public ushort? Amount { get; set; }
    //Json container property. Same type as JsonDictionary<string,object>
    public JsonDictionary Parameters { get; set; } = new();
}

//EF context
public class DataContext : DbContext
{
    public DbSet<Product> Goods { get; set; } = null!;

    public DataContext()
    {
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite($"Data Source=MyApp.db");
    }
}
Clone this wiki locally