Entity Framework Code First: how to map a flat table to a class with nested objects

I have a scenario in which data from one table should be in two objects.

[Table] -Field1 -Field2 -Field3 -Field4 

And the class is as follows:

 [Class1] -Field1 -Field2 -Class2 object here [Class2] -Field3 -Field4 

I set the [NotMapped] attribute in Class1 over the Class2 property, which contains fields 3 and 4. I also added the configuration in the database context:

 public class ConfigurationClass1 : EntityTypeConfiguration<Class1> { public ConfigurationClass1 () { Property(o => o.Class2.Field3).HasColumnName("Field3"); Property(o => o.Class2.Field4).HasColumnName("Field4"); } } 

The problem is that when I try to use the Entity Framework with Class1, I got:

The 'Class2' property is not a declared property in the 'Class2' type. Verify that the property has not been explicitly excluded from the model using the Ignore or NotMappedAttribute annotation data. Verify that this is a valid primitive property.

How can I use the Entity Framework Code First with Entity, which has a nested object with all the information in a flat table?

+8
source share
2 answers

You can only do this if Class2 can be recognized by EF CF as a complex type .

Short:

  • Class2 must not contain references to other EF objects. Only to other complex types or standard types.
  • Class2 cannot be shared. in this case, as a workaround, you can create a non-generic nested class and use it in your class1.
+8
source

ComplexType is missing from EntityFramworkCore. I am using builder.OwnsOne (T). This gives the same T_Property output. :) Link to the document

0
source

Source: https://habr.com/ru/post/917996/


All Articles