Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core fluent mapping to inner object properties

I have a class that contains some properties. For some architectural reasons, I have an instance of another objet into my class.

Simple example

public class MyEntity {
   public MySubEntity SubEntity {get; set;}
}

For this, I create fluent mapping like :

builder.ToTable(MyEntity.CONST_TABLE_NAME);
builder.HasKey(m => m.Id);
builder.Property(m => m.Column1).IsRequired();
builder.Property(m => m.SubEntity.Column2).IsRequired();

I cannot integrate all my subEntity properties into my main entity (my subEntity has its own intelligence). I just want to map my subentity properties, which is NOT stored in a separated table, to myEntity table.

The last line throw an exception :

The expression 'm => m.SubEntity.Column2' is not a valid property expression. The expression should represent a property access: 't => t.MyProperty'.

How can I perform such mapping ?

like image 792
cdie Avatar asked Oct 18 '22 14:10

cdie


1 Answers

EF Core doesn't support this type of mapping for now. It will not be supported in EF Core 1.0 RTM (see my github issue : https://github.com/aspnet/Home/issues/1330)

As I described in my github issue, I figured out 2 solutions :

1) Create a derived class from my model, specialy designed for EF, and expose all properties as simple. It will need more mapping when insert/update and retrieve from Db. We don't choose this option

2) Create proxy properties. In my example, this is like :

public class MyEntity {
   private MySubEntity SubEntity {get; set;}
   public string SubEntityValue 
   { 
     get 
     { 
         return SubEntity.Value;
     } 
     set 
     { 
         SubEntity.Value = value; 
     }
}

This seems to be the best solution (we choose this one).

like image 159
cdie Avatar answered Oct 21 '22 04:10

cdie