I need to store type safe entity key/value pairs in EF Core.
Key Value Types
// KeyValuePair<string,bool>
// KeyValuePair<string,int>
// KeyValuePair<string,string>
// KeyValuePair<string,float>
// KeyValuePair<string,DateTime>
Entity
public class MyEntity
{
public int Id { get; set; }
public List<KeyValuePair<string,T>> Attributes { get; set; }
}
Elsewhere
{
…
dbContext.MyEntity.Add(new KeyValuePair<string,bool>("Active", true);
dbContext.MyEntity.Add(new KeyValuePair<string,string>("Customer", "Microsoft");
dbContext.MyEntity.Add(new KeyValuePair<string,string>("Street", "1 Microsoft Way");
dbContext.MyEntity.Add(new KeyValuePair<string,float>("Rating",5.0);
}
How can this be accomplished in EF Core?
I know it's a bit late for an answer, but I had the same problem trying to persist keyvalue pairs. The only way I found was to strong type them, since EF has no clue on how to persist the KeyValue entity.
Here's my model:
public class Payment
{
//-- Properties
public int PaymentId { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; }
public virtual List<PaymentField> PaymentFields { get; set; } = new List<PaymentField>();
}
public class PaymentField
{
//-- Properties
[Key]
public int PaymentFieldId { get; set; }
// References master table
public int PaymentId { get; set; }
public virtual Payment Payment { get; set; }
public virtual List<PaymentFieldItem> PaymentFieldItems { get; set; } = new List<PaymentFieldItem>();
}
public class PaymentFieldItem
{
public int PaymentFieldItemId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public int PaymentFieldId { get; set; }
public virtual PaymentField PaymentField { get; set; }
}
Hope you can adjust to your own needs.