实体框架代码首先:如何使用嵌套对象将平面表映射到类 [英] Entity Framework Code First : How to map flat table to class with nested objects

查看:160
本文介绍了实体框架代码首先:如何使用嵌套对象将平面表映射到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,一个表中的数据必须在两个对象中。

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

[Table]
-Field1
-Field2
-Field3
-Field4

课堂看起来像这样:

[Class1]
-Field1
-Field2
-Class2 object here

[Class2]
-Field3
-Field4

我已经将Class1中的属性[NotMapped]设置在包含字段3和4的Class2的属性上。我还在数据库上下文中添加了配置:

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");
    }
}

问题是当我尝试使用Entity Framework与Class1我得到:

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


属性Class2不是类Class2上声明的属性。
通过使用Ignore方法或NotMappedAttribute数据
注释,验证该属性尚未从
模型中明确排除。确保它是一个有效的原始属性。

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?

推荐答案

只有在Class2可以被EF CF识别为< a href =http://weblogs.asp.net/manavi/archive/2011/03/28/associations-in-ef-4-1-code-first-part-2-complex-types.aspx = noreferrer>复杂类型。

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

简要地说:


  1. Class2不应包含对其他EF实体的任何引用。其他复杂类型或标准类型只有

  2. Class2不能是通用的。在这种情况下,您可以创建一个非泛型的嵌套类并在Class1中使用它。

这篇关于实体框架代码首先:如何使用嵌套对象将平面表映射到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆