Skip to content

Instantly share code, notes, and snippets.

@hikalkan
Created March 29, 2018 10:51
Show Gist options
  • Save hikalkan/abbe63206e64b6c116fc8001e6a8b820 to your computer and use it in GitHub Desktop.
Save hikalkan/abbe63206e64b6c116fc8001e6a8b820 to your computer and use it in GitHub Desktop.
How to map a dictionary property of an entity to a string field of a table in Entity Framework Core v2.1+
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>(b =>
{
b.Property(u => u.UserName).IsRequired().HasMaxLength(128);
b.Property(u => u.ExtraProperties)
.HasConversion(
d => JsonConvert.SerializeObject(d, Formatting.None),
s => JsonConvert.DeserializeObject<Dictionary<string, object>>(s)
)
.HasMaxLength(4000)
.IsRequired();
});
}
}
public class Program
{
public static void Main(string[] args)
{
using (var context = new MyDbContext(CreateDbContextOptions()))
{
var userJohn = new User("john");
var userNeo = new User("neo")
{
ExtraProperties =
{
["Age"] = 42
}
};
context.Users.Add(userJohn);
context.Users.Add(userNeo);
context.SaveChanges();
}
using (var context = new MyDbContext(CreateDbContextOptions()))
{
foreach (var user in context.Users)
{
Console.WriteLine(user);
}
}
Console.ReadLine();
}
public static DbContextOptions<MyDbContext> CreateDbContextOptions()
{
return new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer("Server=localhost;Database=EfCoreValueConverterDemo;Trusted_Connection=True;MultipleActiveResultSets=true")
.Options;
}
}
public class User
{
public Guid Id { get; set; }
public string UserName { get; set; }
public Dictionary<string, object> ExtraProperties { get; set; }
public User()
{
Id = Guid.NewGuid();
ExtraProperties = new Dictionary<string, object>();
}
public override string ToString()
{
return "# User: " + JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
@sophisma
Copy link

Thank you for sharing this.
You should be aware of a drawback though.
If you want to query your database directly to search for users with a certain property, you can't do it in a clean way.

@sfmskywalker
Copy link

Brilliant. Thanks for sharing this.

@hikalkan
Copy link
Author

You're welcome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment