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

时光毁灭记忆、已成空白 提交于 2019-12-04 19:00:41

问题


I have the scenario where the data from a single table must be in 2 objects.

[Table]
-Field1
-Field2
-Field3
-Field4

And the class look like this:

[Class1]
-Field1
-Field2
-Class2 object here

[Class2]
-Field3
-Field4

I have set in the Class1 the attribute [NotMapped] over the property of the Class2 which contain the field 3 and 4. I also have 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 Entity Framework with the Class1 I got :

The property 'Class2' is not a declared property on type 'Class2'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.

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


回答1:


You can do like this only in case Class2 can be recognized by EF CF as a Complex type.

Briefly:

  1. Class2 shouldn't contain any references to other EF Entities. Only to other Complex types or standard types
  2. Class2 can't be generic. in this case as a workaround you can create a non-generic nested class and use it in your Class1.


来源:https://stackoverflow.com/questions/11018794/entity-framework-code-first-how-to-map-flat-table-to-class-with-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!