Answer the question
In order to leave comments, you need to log in
How to map property of type 'Dictionary' in Entity Framework?
using Microsoft.EntityFrameworkCore;
namespace NameSpaceName
{
public class WordContext : DbContext
{
public DbSet<VmWord> Words { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=NameSpaceName.db");
}
}
}
namespace NameSpaceName
{
public class VmWord
{
public int Id { get; set; }
public string Name { get; set; }
public Dictionary<string, string> Localization { get; set; }
}
}
word.Localization["en"];
The property 'VmWord.Localization' could not be mapped, because it is of type 'Dictionary' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Answer the question
In order to leave comments, you need to log in
Are you going to store a whole array in one field? And then, to get one value, will you read the entire array from the field?
This is not the right approach, but it can be implemented by serializing the array to json when writing and when reading - deserialization. For example:
public class VmWord
{
public int Id { get; set; }
public string Name { get; set; }
public string Localization { get; set; }
[NotMapped]
public Dictionary<string, string> Localizations
{
get { return JsonConvert.DeseriazeObject<Dictionary<string, string>>(Localization.ToList()); }
set { Localization = JsonConvert.SerializeObject(value); }
}
}
public class VmWord
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<string> Localizations { get; set; }
}
public class Localization
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public virtual VmWord VmWord { get; set; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question