How to save an Expando object field with Entity Framework Core

c# entity-framework entity-framework-core

Question

I have a class with an ExpandoObject field to allow users of my class to add their properties to it.

public class Employee
{
    public dynamic ExtendedProperties = new ExpandoObject();

    public int Id { get; set; }

    public string Name { get; set; }
}

I want to map these extended properties to columns in the database. How can I save these extended properties with Entity Framework Core 2.1 ?

1
0
12/2/2018 6:38:40 PM

Accepted Answer

You would map this to an XML or JSON column in the database and use an EF Core Value Conversion.

1
12/2/2018 8:08:14 PM

Popular Answer

First of all, Entity Framework Core wasn't designed for such behaviour. The main idea of EF Core (and EF too) is to map table columns on class properties and vice versa. It is needed to realize dynamic class building to obtain what you need.

However, I think, we can implement something like dynamic properties. I see two ways.

Way 1:

You can make a single table with fields Name, Value (and, maybe, Type) and store your properties in it. It's your responsibilities to store and select them in CRUD operations.

Way 2:

Second approach is more complicated but more interesting too. It assumes creating physical fields in database, and, therefore, may be suitable if your database can be used by other applications (including legacy ones). I'm trying to implement this behaviour right now in one my project, but the work is not finished yet and I don't know about all underwater rocks that will wait in front. What you will need.

1) EntityFramework.Triggers library from @NickStrupat. This library gives a possibility to work with events during insert/update/delete operations.

2) A table FieldsDefinitions - it will contains metadata for all additional properties. This table should have triggers for insert/delete, in which SQL DDL commands for changing DB structure will be executed. SQL sentence will be build automatically based on your dictionary data.

3) Something like Dictionary<FieldDefinition, string> CustomFields {get;set;} in your Employee class.

4) Insert/update triggers for Employee entity should run DML commands to update the real fields. SQL sentence will be build automatically based on your dictionary data.

5) Every select operation should update custom fields. Need to say you honestly - it can be a bottleneck when selecting huge data amount, I didn't solve this problem yet.

P.S.

While I writed this post, the answer from @DavidBrowne was appeared, and this one seems to be the most elegant solution. But I decided to leave my answer to live :) - it can be suitable for someone who use EF Core below 2.1 or EF.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow