Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF: mapping class properties to Rows not Columns

Do you have an idea how to map properties of a class to rows in a table? Let's have a table [ID, KEY, VALUE].

I would like to have for predefined key values (on attributes for example) mapped properties in a class, with values taken from value column.

EXAMPLE:

Table

 ---------------------------------
| ID  | Key        | Value        |
 ---------------------------------
| 1   | Name       | Jon          |
 ---------------------------------
| 2   | Surname    | Doe          |
 ---------------------------------

Class

public class Bar
{
    public string Name { get; set; }
    public string Suname { get; set; }
}

Is there anything in EF to achieve this or do I have to write my own custom code?

BR

like image 747
mdzieg Avatar asked Nov 01 '22 14:11

mdzieg


1 Answers

You can't map values from column to properties. Thus you have key-value table, then I suggest you to read table content into dictionary.

First, you should have entity with properties which correspond to table column names:

public class Foo
{
   public string Key { get; set; }
   public string Value { get; set; }
}

After you map this entity to your table, you can read all table content into dictionary:

var values = context.Foos.ToDictionary(f => f.Key, f => f.Value);

Now you can easily get values by keys:

var name = values["Name"];

You can even use this dictionary as backing store for your properties:

public void Bar
{
    private Dictionary<string, string> values = 
         context.Foos.ToDictionary(f => f.Key, f => f.Value);

    public string Name { get { return values["Name"]; } }
    public string Surname { get { return values["Surname"]; } }
}
like image 77
Sergey Berezovskiy Avatar answered Nov 08 '22 04:11

Sergey Berezovskiy