EF Core fluent mapping to inner object properties

c# entity-framework-core fluent-entity-framework

Question

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 ?

1
5
2/25/2016 3:51:07 PM

Accepted Answer

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).

3
3/1/2016 9:47:01 AM


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