M
M
mr_blond972018-10-15 11:28:54
ORM
mr_blond97, 2018-10-15 11:28:54

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; }
    }
}

You must have access to the Localization element by key:
word.Localization["en"];

When adding a migration:
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'.

How to map property of type 'Dictionary' in Entity Framework?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-10-15
@mr_blond97

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); }
    }
}

But the correct approach would be:
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; }
}

And get the key later:
context.VmWord.Localizations.FirstOrDefault(x => x.Key == key)?.Value;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question