繁体   English   中英

EF Core - 具有动态属性的实体

[英]EF Core - Entity with Dynamic Properties

我正在尝试找出处理动态数据的最佳方法,并将其存储在 db 中。

例如,假设一辆汽车,有我们想要捕获的必填字段,例如 used、model、cost,但是还有构成汽车的所有其他方面以及我们想要捕获的其独特性各不相同,例如一辆车可能有或没有的车顶类型(玻璃、布或金属)或前灯(霓虹灯、LED 等)。

创建实体以捕获此动态数据的最佳方法是什么。

目前我只是将所有内容存储在一个 JSON 字符串中

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 
}

这一直有效,直到最近,现在我希望能够以 Key:Value 格式查询可能具有 0...N 个特征的特征列表。

应对这一挑战的更有效方法是什么?

  1. 您可以使用支持存储和查询 JSON 数据的数据库,例如 PostGreSQL

  2. 然后,您可以将建议的模式用于不稳定数据( 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();
}

查询将如下所示:

// .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);

只要记住正确索引。

使用 PostgreSQL 数据库,添加:

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

并在需要访问值时使用序列化和反序列化:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM